If you have worked with React before, you may be familiar with the older API where the
ref
attribute is a string, for example ref={'textInput'}
, and the DOM node is accessed as this.refs.textInput
. We do not advise this, because string refs have the problems below and are considered legacy. String refs were removed in React v16
.
- They force React to keep track of the currently executing component . This is problematic because it makes the react module stateful, and thus causes strange errors when the react module is duplicated in the bundle.
- They are not composable - if a library puts a ref on a passed child element, the user cannot add another ref to it. Callback refs compose perfectly.
- They do not work with static analysis, such as Flow. Flow cannot guess the magic the framework uses to map a string ref onto
this.refs
, nor its type (which may differ). Callback refs are friendlier to static analysis.
- It does not work the way most people expect with the render callback pattern (for example)
class MyComponent extends Component {
renderRow = (index) => {
// This will not work. The ref will be attached to DataTable, not to MyComponent:
return <input ref={'input-' + index} />;
// This will work, though! Callback refs are great.
return <input ref={input => this['input-' + index] = input} />;
}
render() {
return <DataTable data={this.props.data} renderRow={this.renderRow} />
}
}
Comments