I'm wondering what's the best practice for accessing the DOM elements inside my render function from the same component. Note that I will be rendering this component multiple times on a page.
e.g.
var TodoItem = React.createClass({
...
render:function(){
function oneSecLater(){
setTimeout(function(){
//select the current className? this doesn't work, but it gives you an idea what I want.
document.getElementsByClassName('name').style.backgroundColor = "red";
)}, 1000);
}
return(
<div className='name'>{this.oneSecLater}</div>
)
})
You can make use of
ref callback
to access the dom element in react, which is what React Docs recommend to followand do that in the
componentDidMount
lifecycle function as refs won't be accessible before the DOM is createdDOCS
You can use
ReactDOM.findDOMNode(this)
to access the underlying DOM node. But accessing the DOM node and manipulating like you do is against the React style of programming. It's better to use a state variable and called thesetState
method to re-render the DOM.here is my solution: To get a computedCss of an specific element, you need to add a ref attribute to the elemenet first.
enter image description here
And then, in the componentDidUpdate() function, get your element's css by using window.getComputedStyle(this.refs.lineChartWrap).XXX enter image description here
Here, no need to use setTimeout. There are lifecycle methods for component, of which
componentDidMount
is called after the render. So, you can get the reference to your div in the method.