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> ) })
Accessing DOM nodes in the same React component. To create a reference to a DOM node in a component we can do it either using the useRef() hook, which for most cases is the easier and best approach, or using the callback ref pattern which gives you more control when refs are set and unset.
In React we can access the DOM element using Refs. Refs provide a way to access DOM nodes or React elements created in the render method. Creating Refs: Refs are created using React. createRef() and attached to React elements via the ref attribute.
When you return multiple elements from React elements from the render method, the assumtion that the tree will have one root node for the Component will not longer hold, hence making it difficult to process reconcilation algorithm. Thus react gives you a limitation to provide a root node.
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 the setState
method to re-render the DOM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With