What is the difference/advantages/disadvantages between using:
React.findDOMNode(this.refs.elementReferenceName)
and
document.getElementById(elementId)
when using ReactJS?
What is the difference/advantages/disadvantages between using:
React.findDOMNode(this.refs.elementReferenceName)
and
document.getElementById(elementId)
when using ReactJS?
Share Improve this question edited Mar 28, 2018 at 16:16 Joseph Quinsey 9,97210 gold badges56 silver badges80 bronze badges asked Aug 11, 2015 at 17:43 esanz91esanz91 8932 gold badges12 silver badges24 bronze badges 3-
1
findDOMNode
(in normal circumstances) 1) make some checks and fails in a normal way if those fail; 2) fills out the internal cache (nodeCache
) object.getElementById
, apparently, doesn't do any of those - it just returnsnull
if nothing's found. – raina77ow Commented Aug 11, 2015 at 17:56 - This is just a note not answer: findDOMNode() only works on mounted ponents (that is, ponents that have been placed in the DOM). If you try to call this on a ponent that has not been mounted yet (like calling findDOMNode() in render() on a ponent that has yet to be created) an exception will be thrown. – anam Commented Aug 11, 2015 at 17:58
- It lets you find the Dom node by element reference instead of id. What if your ponent has no classes or ids, or it does but you are unaware of them in current context? – Mike Driver Commented Aug 11, 2015 at 18:41
1 Answer
Reset to default 6The main advantage and reason to use React.findDOMNode
is that it stays within the React paradigm, since you pass it a ponent--And in most cases you are dealing with React ponents (either handling a lifecycle function or calling a function that is implemented in the ponent 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 ponent is not mounted) will raise an exception. OTOH, document.getElementById
won't throw an exception if the ponent 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