47 lines
2.0 KiB
Plaintext

== Why is this an issue?
React Refs provide a way to access DOM nodes or React elements created in the render method.
Older React versions allowed the ref attribute to be a string, like `"textInput"`, later accessible as `this.refs.textInput`. This is considered legacy code due to multiple reasons:
* String `refs` make React slower as they force React to keep track of what component is currently executing.
* String `refs` are not composable: if a library puts a ref on the passed child, the user can't put another ref on it.
* The owner of a string `ref` is determined by the currently executing component.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
const Hello = createReactClass({
componentDidMount() {
const component = this.refs.hello; // Noncompliant
// ...
},
render() {
return <div ref="hello">Hello, world.</div>;
}
});
----
Instead, reference callbacks should be used. These do not have the limitations mentioned above. When the DOM node is added to the screen, React will call the `ref` callback with the DOM node as the argument. When that DOM node is removed, React will call your `ref` callback with `null`. One should return `undefined` from the `ref` callback.
[source,javascript,diff-id=1,diff-type=compliant]
----
const Hello = createReactClass({
componentDidMount() {
const component = this.hello;
// ...
},
render() {
return <div ref={(c) => { this.hello = c; }}>Hello, world.</div>;
}
});
----
== Resources
=== Documentation
* React Documentation - https://react.dev/reference/react-dom/components/common#ref-callback[`ref` callback function]
* React Documentation - https://legacy.reactjs.org/docs/refs-and-the-dom.html[Refs and the DOM]
* React Documentation - https://react.dev/learn/manipulating-the-dom-with-refs[Manipulating the DOM with Refs]
* React Documentation - https://react.dev/reference/react/useRef[`useRef`]
* React Documentation - https://react.dev/reference/react/createRef#createref[`createRef`]