I have been trying to integrate the JSONEditor into a React TypeScript application. The working sample of React JavaScript version is available at https://github.com/josdejong/jsoneditor/blob/master/examples/react_demo/src/JSONEditorDemo.js (and reproduced below). I have since ported the code into React TypeScript as under. Am I doing the right thing? Are any further improvements recommended?
React JavaScript version
import React, {Component} from 'react';
import JSONEditor from 'jsoneditor';
import 'jsoneditor/dist/jsoneditor.css';
import './JSONEditorDemo.css';
export default class JSONEditorDemo extends Component {
componentDidMount () {
const options = {
mode: 'tree',
onChangeJSON: this.props.onChangeJSON
};
this.jsoneditor = new JSONEditor(this.container, options);
this.jsoneditor.set(this.props.json);
}
componentWillUnmount () {
if (this.jsoneditor) {
this.jsoneditor.destroy();
}
}
componentDidUpdate() {
this.jsoneditor.update(this.props.json);
}
render() {
return (
<div className="jsoneditor-react-container" ref={elem => this.container = elem} />
);
}
}
React TypeScript version
export const Editor = (props: IProps) => {
const mode : JSONEditorMode = "tree";
const elRef = React.useRef<HTMLDivElement | null>(null);
const editorRef = React.useRef<JSONEditor | null>(null);
const unmountEditor = () => {
editorRef.current?.destroy();
}
React.useEffect(() => {
//const container = document.getElementById("jsoneditor");
const container = elRef.current;
const options : JSONEditorOptions = {
mode: mode,
onChangeJSON: props.onChangeJSON,
};
if (container) {
const jsonEditor = new JSONEditor(container, options);
jsonEditor.set(props.json);
editorRef.current = jsonEditor;
}
return unmountEditor;
}, [props]);
return <div id="jsoneditor" ref={elRef} className="jsoneditor-react-container" />;
};