What is the difference/advantages/disadvantages between using:
React.findDOMNode(this.refs.elementReferenceName)
and
document.getElementById(elementId)
when using ReactJS?
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 .
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.
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.
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.
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
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