Skip to content

Instantly share code, notes, and snippets.

@Jezternz
Created February 3, 2024 04:16
Show Gist options
  • Save Jezternz/fd2edd87f9b31c66eb9258d75afed600 to your computer and use it in GitHub Desktop.
Save Jezternz/fd2edd87f9b31c66eb9258d75afed600 to your computer and use it in GitHub Desktop.
ReactJsonEditor
import React, { useEffect, useMemo, useRef, useState } from "react";
import JSONEditor from "jsoneditor/dist/jsoneditor";
import "jsoneditor/dist/jsoneditor.css";
/* Minimal React Wrapper for 'jsoneditor' (https://www.npmjs.com/package/jsoneditor) */
// Uncontrolled Usage Example:
// return <ReactJsonEditor value={value}/>;
// Controlled Usage Example:
// const [value, setValue] = useState({});
// const opts = useMemo(
// () => ({ onChangeJSON: newValue => setValue(newValue) })
// , [setValue]
// )
// return <ReactJsonEditor value={value} options={opts}/>;
const defaultOptions = {
mode: 'tree'
, history: true
, search: true
, navigationBar: true
, statusBar: true
, sortObjectKeys: false
};
export const ReactJsonEditor = ({
// value - json value
// - Updated to value will not affect editor state
value
// options - for possible options see https://github.com/josdejong/jsoneditor/blob/master/docs/api.md
// - Updates to options will cause a recreation of the editor
, options
// containerRef - optionally set a react ref for the container <div>
, containerRef
// getJsonEditor - optional function which will be called when the internal json editor instance is replaced (with its instance).
, getJsonEditor
}) => {
const innerRef = useRef(null);
const optionalContainerRef = containerRef || innerRef;
let [jsonEditor, setJsonEditor] = useState(null);
let [valueInitialized, setValueInitialized] = useState(false);
const compiledOptions = useMemo(() => ({ ...defaultOptions, ...options }), [options]);
useEffect(
() => {
if (optionalContainerRef.current) {
const editor = new JSONEditor(optionalContainerRef.current, compiledOptions);
setJsonEditor(editor);
}
},
[optionalContainerRef, setJsonEditor, compiledOptions]
);
useEffect(
() => {
if (jsonEditor && value) {
if (!valueInitialized) { jsonEditor.set(value); setValueInitialized(true); }
else { jsonEditor.update(value); }
}
},
[jsonEditor, value, valueInitialized, setValueInitialized]
);
useEffect(
() => {
if (jsonEditor && typeof getJsonEditor === "function") {
getJsonEditor(jsonEditor);
}
},
[jsonEditor, getJsonEditor]
);
return (
<div ref={optionalContainerRef} style={{ width: '100%', height: '100%' }} />
);
};
export default ReactJsonEditor;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment