in either the WillMount component or componentDidMount . document.g...">

Unable to manage DOM in React component

I cannot manipulate <div id="chart"> in either the WillMount component or componentDidMount .

document.getElementById("chart") returns null in both methods. Should I not use the raw DOM manipulation function, or should I use something else to achieve the same as controlling <div id="chart">

 import React from 'react' export default class D3Chart extends React.Component { constructor () { super(); } componentWillMount() { document.getElementById("chart").innerText = "Testing"; } componentDidMount () { document.getElementById("chart").innerText = "Testing"; } render() { return (<div id="chart"></div> ) }; } 
+5
source share
2 answers

Just use ref , as the React guys recommend :

 import React from 'react'; import ReactDOM from 'react-dom'; export default class D3Chart extends React.Component { constructor () { super(); } componentDidMount () { this.refs.chart.innerText = "Testing"; } render() { return <div id="chart" ref="chart"></div>; } } 

And here is the fiddle .

+14
source

Link to how you access node, similar to id in HTML

 this.refs.myDiv; <div ref='myDiv' /> 

and key is how React distinguishes between similar nodes. The cloneElement method (used to add additional details to the JSX template instance) supports these links, so you don’t have to worry about the β€œloss” of object references.


Also in a more complex / different / next gene light:

When you attach [ref] to a DOM component, such as <div /> , you return a DOM node; when attaching [ref] to a composite component, for example <TextInput /> , you will get an instance of the React class. In the latter case, you can call methods on this component if they appear in the class definition.

 render () { return ( <div ref={htmlOrComponent => { this.htmlOrComponent = htmlOrComponent }} ); } componentDidMount () { // this.htmlOrComponent is either the HTML or null } 

+5
source

All Articles