6

What is the difference/advantages/disadvantages between using:

  React.findDOMNode(this.refs.elementReferenceName)

and

  document.getElementById(elementId)

when using ReactJS?

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
esanz91
  • 893
  • 2
  • 12
  • 24
  • 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 returns `null` if nothing's found. – raina77ow Aug 11 '15 at 17:56
  • This is just a note not answer: findDOMNode() only works on mounted components (that is, components that have been placed in the DOM). If you try to call this on a component that has not been mounted yet (like calling findDOMNode() in render() on a component that has yet to be created) an exception will be thrown. – anam Aug 11 '15 at 17:58
  • It lets you find the Dom node by element reference instead of id. What if your component has no classes or ids, or it does but you are unaware of them in current context? – Mike Driver Aug 11 '15 at 18:41

1 Answers1

6

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

Ed Ballot
  • 3,405
  • 1
  • 17
  • 24