Ad

ReactJS Integration With Libraries Using GetElementById

- 1 answer

What is the best approach for rendering components using libraries for which direct access to the DOM is required (e.g. document.getElementById()) ? Currently I got things working thanks to setTimeout :

class MyComponent extends React.Component {
    render(){
        setTimeout(function(){
            myCoolGraphLibrary.createChart({
                container : "myChartContainer",
                series : [...],
                ...
            });    
        },1000);
        return (<div id="myChartContainer"></div>);
    }
}

Without setTimeout, the container is not yet available in the DOM so the call to createChart fails.

Is there a better design pattern for achieving this ?

Ad

Answer

Use the lifecycle methods. https://facebook.github.io/react/docs/component-specs.html

In particular, you'll want to use componentDidMount to run any code that depends on the DOM elements existing. If you're adding event listeners, be sure to remove them in componentWillUnmount

EDIT: In response to your comment, your code would look like this:

class MyComponent extends React.Component {
    componentDidMount() {
        myCoolGraphLibrary.createChart({
            container : "myChartContainer",
            series : [...],
            ...
        });
    }
    render() {
        return (<div id="myChartContainer"></div>);
    }
}
Ad
source: stackoverflow.com
Ad