In React, findDOMNode is used to get the browser DOM node given a component instance. However, using findDOMNode is
fragile because the connection between the JSX node and the code manipulating the corresponding DOM node is not explicit. For example, changing the
external structure of returned JSX will affect the return value of findDOMNode. There are also other caveats when using findDOMNode.
import { Component } from 'react';
import { findDOMNode } from 'react-dom';
class AutoselectingInput extends Component {
componentDidMount() {
const input = findDOMNode(this); // Noncompliant: findDOMNode is deprecated
input.select();
}
render() {
return <input defaultValue="Hello" />
}
}
Instead, one should get the component’s own DOM node from a ref. Pass your ref as the ref attribute to the JSX tag for which you want
to get the DOM node. This tells React to put this <input>’s DOM node into inputRef.current.
Use createRef to manage a specific DOM node. In modern React without class components, the equivalent code would call
useRef instead.
import { createRef, Component } from 'react';
class AutoselectingInput extends Component {
inputRef = createRef(null);
componentDidMount() {
const input = this.inputRef.current; // Always points to the input element
input.select();
}
render() {
return (
<input ref={this.inputRef} defaultValue="Hello" />
);
}
}