Last active
April 11, 2018 03:28
-
-
Save dapicester/af644ce12b8340ca0d894df7d1fbc9b0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 from 'react' | |
import { isEqual, template } from 'lodash' | |
// This is a DOM library, some plumbing with refs is required. | |
import 'json-editor' | |
// Get the imported reference from the global namespace. | |
const JSONEditor = window.JSONEditor | |
// Set sensible defaults | |
JSONEditor.defaults.options.show_errors = 'always'; | |
JSONEditor.defaults.options.template = { | |
// lodash template engine | |
compile: string => variables => template(string)(variables) | |
} | |
JSONEditor.defaults.options.theme = 'bootstrap3'; | |
JSONEditor.defaults.options.iconlib = 'bootstrap3'; | |
/** | |
* Usage: | |
* <JsonEditor schema={schema} value={value} onChange={handleChange} /> | |
*/ | |
class JsonEditor extends React.Component { | |
/// Initialize the editor with the schema. | |
componentDidMount() { | |
this.initEditor() | |
} | |
/// Should update only if schema changes. | |
shouldComponentUpdate(nextProps) { | |
return !isEqual(this.props.schema, nextProps.schema) | |
} | |
/// Re-initialize the editor with the new schema. | |
componentDidUpdate() { | |
this.destroyEditor() | |
this.initEditor() | |
} | |
/// Release resources. | |
componentWillUnmount() { | |
this.destroyEditor() | |
} | |
setRef = el => { | |
this.container = el | |
} | |
handleChange = () => { | |
this.props.onChange({ | |
data: this.editor.getValue(), | |
}) | |
} | |
destroyEditor = () => { | |
if (this.editor) { | |
this.editor.destroy() | |
this.editor = null | |
} | |
} | |
initEditor = () => { | |
const { schema, value } = this.props | |
if (!schema) { | |
this.destroyEditor() | |
return | |
} | |
const editor = new JSONEditor(this.container, { | |
schema, | |
startval: value.data || [] | |
}) | |
editor.on('change', this.handleChange) | |
this.editor = editor | |
} | |
render() { | |
return ( | |
<div ref={this.setRef} /> | |
) | |
} | |
// TODO: add button to revert to pristine data | |
// TODO: add button to clear data | |
} | |
export default JsonEditor |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi @dapicester,
Thank you for this, but doesn't quite work for me. When I include this component and reference as follows:
I get the following error
Also it seems createRef function changed as of 16.3.x wmonk/create-react-app-typescript#293
Thoughts?
TJ