Avoid usage of `findDOMNode`JS-0445
React findDOMNode
method is already deprecated in favor of StrictMode
. It’s important to eliminate all its usages in the codebase to be ready to migrate to the future React versions.
The simplest solution is to replace it with a ref
attached to the element you are interested in referencing (or a wrapper). But, if you have to migrate an extensive and complex application, this may not work in all cases. In those scenarios, solutions like using ref
forwarding or explicitly passing the ref as a prop can save some time.
** Refactoring Hazard with findDOMNode
**
findDOMNode
breaks the abstraction levels of a class component by allowing a parent to demand that specific children be rendered. It creates a refactoring hazard where you can’t change the implementation details because a parent might be reaching into its DOM node. findDOMNode
only returns the first child. Still, with Fragments
, a component can render multiple DOM nodes.
findDOMNode
is a one-time read API. It only gives you an answer when you ask for it. If a child component renders a different node, there is no way to handle this change. Therefore findDOMNode
only works if components always return a single DOM node that never changes.
Bad Practice
class MyComponent extends Component {
componentDidMount() {
findDOMNode(this).scrollIntoView();
}
render() {
return <div />
}
}
Recommended
class MyComponent extends Component {
componentDidMount() {
this.node.scrollIntoView();
}
render() {
return <div ref={node => this.node = node} />
}
}