ReactJS Integration with Libraries Using getElementById

What is the best approach for rendering components using libraries that require direct access to the DOM (e.g. document.getElementById())? Currently I got a job 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 createChart call failed.

Is there a better design for this?

+4
source share
1 answer

Use life cycle methods. https://facebook.imtqy.com/react/docs/component-specs.html

, componentDidMount , DOM. , componentWillUnmount

EDIT: :

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

Source: https://habr.com/ru/post/1622779/


All Articles