Skip to content

Instantly share code, notes, and snippets.

@dapicester
Last active April 11, 2018 03:28
Show Gist options
  • Save dapicester/af644ce12b8340ca0d894df7d1fbc9b0 to your computer and use it in GitHub Desktop.
Save dapicester/af644ce12b8340ca0d894df7d1fbc9b0 to your computer and use it in GitHub Desktop.
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
@tkuben
Copy link

tkuben commented Apr 11, 2018

Hi @dapicester,

Thank you for this, but doesn't quite work for me. When I include this component and reference as follows:

<Dialog
    title="Component Schema"
    modal={true}
    open={this.state.showDialog}
    autoScrollBodyContent={true}
>
<JsonEditor
    schema={this.state.baseComponentSchema}
    value={this.state.baseComponentSchemaValue}
    onChange={this.handleEditorSubmit}
/>
</Dialog>

I get the following error

Uncaught TypeError: Cannot set property 'container' of undefined

Also it seems createRef function changed as of 16.3.x wmonk/create-react-app-typescript#293

Thoughts?
TJ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment