Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference with using ref and document.getElementById, ect when using ReactJS?

What is the difference/advantages/disadvantages between using:

  React.findDOMNode(this.refs.elementReferenceName)

and

  document.getElementById(elementId)

when using ReactJS?

like image 838
esanz91 Avatar asked Aug 11 '15 17:08

esanz91


People also ask

Is it OK to use document getElementById in React?

The equivalent of the document. getElementById() method in React is using refs. To select an element, set the ref prop on it to the return value of calling the useRef() hook and access the dom element using the current property on the ref , e.g. ref. current .

Is it bad to use document querySelector in React?

Conclusion. You can use the querySelector and querySelectorAll within React. The downside it that you can lose the reference to the DOM element due to Reacts Reactivity. The solution is to use the useRef hook provided by react to store a reference to the DOM element.

What can I use in React instead of document getElementById?

In React we have a concept of Refs which is equivalent to document. getElementById() in Javascript. Refs provide a way to access DOM nodes or React elements created in the render method. Refs are created using React.

When should you use React refs?

They are used in cases where we want to change the value of a child component, without making use of props and all. They also provide us with good functionality as we can use callbacks with them. We can create a Ref by the following three methods: Using React.


1 Answers

The main advantage and reason to use React.findDOMNode is that it stays within the React paradigm, since you pass it a component--And in most cases you are dealing with React components (either handling a lifecycle function or calling a function that is implemented in the component descriptor).

Relying on the id in a DOM element breaks encapsulation in React because it doesn't use id.

That being said, it is up to you and your specific app's needs to determine which is best to use. As with other React functions, you do have to be careful because the calling React.findDOMNode at the wrong time (in render or if the component is not mounted) will raise an exception. OTOH, document.getElementById won't throw an exception if the component is unmounted; but it could return the wrong element if multiple elements exist with that id.

If you haven't yet found it, here is documentation for findDOMNode.

Also, here is the implementation of findDOMNode

like image 158
Ed Ballot Avatar answered Nov 14 '22 23:11

Ed Ballot