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.
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.
const Hello = createReactClass({
componentDidMount() {
const component = this.hello;
// ...
},
render() {
return <div ref={(c) => { this.hello = c; }}>Hello, world.</div>;
}
});