53 lines
2.0 KiB
Plaintext
53 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
||
|
||
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 https://react.dev/reference/react-dom/findDOMNode#caveats[caveats] when using `findDOMNode`.
|
||
|
||
[source,javascript,diff-id=1,diff-type=noncompliant]
|
||
----
|
||
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.
|
||
|
||
[source,javascript,diff-id=1,diff-type=compliant]
|
||
----
|
||
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" />
|
||
);
|
||
}
|
||
}
|
||
----
|
||
|
||
== Resources
|
||
=== Documentation
|
||
|
||
* React Documentation - https://react.dev/reference/react-dom/findDOMNode[`findDOMNode`]
|
||
* React Documentation - https://react.dev/reference/react/createRef[`createRef`]
|
||
* React Documentation - https://react.dev/reference/react/useRef[`useRef`]
|
||
* React Documentation - https://react.dev/learn/manipulating-the-dom-with-refs[Manipulating the DOM with Refs]
|