Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React, how to access the DOM element in my render function from the same component

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>         )    }) 
like image 393
wonghenry Avatar asked Feb 15 '17 06:02

wonghenry


People also ask

How do you access the DOM element in a React functional component?

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.

How do you access a specific DOM element in React?

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.

Why does React only allow one DOM element to be rendered?

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.


1 Answers

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.

like image 125
VJAI Avatar answered Sep 22 '22 00:09

VJAI