Created
February 3, 2024 04:16
-
-
Save Jezternz/fd2edd87f9b31c66eb9258d75afed600 to your computer and use it in GitHub Desktop.
ReactJsonEditor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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