Created
July 6, 2017 07:08
-
-
Save codervince/aea1a77e316bd9b4a085d74a7329a2ff to your computer and use it in GitHub Desktop.
Creating an external wrapper to am npm component not written for react
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
//implements API, looks like a regular R component | |
//just displays data as JSON | |
//uses JSON-Formatter.js https://github.com/mohsen1/json-formatter-js | |
//bundler must have acess to node_modules/dist/bundle.js | |
//bind in HTML via <script) | |
//JSONViewer.js | |
export class JSONViewer extends React.Component { | |
consrtuctor(props){ | |
super(props) | |
} | |
//one prop required pnly | |
static get defaultProps(){ | |
return { | |
data: {} | |
} | |
} | |
componentDidMount(){ | |
//process as shown in DOCS...new formatter object with data, render object | |
//last line appends child to DOM | |
//DOM accessed via ref attribute. this.refs.viewer | |
const formatter = new JSONFormatter(this.props.data); | |
this._child = formatter.render(); | |
this.refs.viewer.appendChild(this._child) | |
} | |
//component must respond to updates | |
componentDidUpdate(prevProps, prevState){ | |
if (this.props.data !== prevProps.data){ | |
const formatter = new JSONFormatter(this.props.data); | |
const newChild = formatter.render() | |
this.refs.viewer.replaceChild(newCHild, this._child) | |
this._child = newChild; | |
} | |
render(){ | |
return ( | |
... | |
<div ref="viewer"></div> | |
) | |
} | |
//App.js | |
import {JSONViewer} from './JSONViewer'; | |
render(){ | |
<JSONViewer date={this.state.products} /> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment