React refs - Tuong-Nguyen/JavaScript-Structure GitHub Wiki
ref
returned from ReactDOM.render
The ReactDOM.render()
will return a reference to our component's backing instance- For stateless components, it returns
null
ref
String Attribute
The Note:
ref
string attribute is not deprecated but will be likely deprecated in the future. Callback refs are preferred.
Usage
- Assign a
ref
attribute to anything returned from render
<input ref="myInput" />
- Access the backing instance via
this.refs
let input = this.refs.myInput;
Note: Do not access
refs
incomponentWillMount
, in this state, the element have not been rendered yet.
ref
Callback Attribute
The ref
attribute can be a callback function- Callback will be executed immediately after the component is mounted
- Referenced element will be passed in as a parameter
- For stateless component, this is the only way for parent access element of child component.
render() {
return (
<input ref={(c) => this._input = c} />
);
}
componentDidMount() {
this._input.focus();
}
Note: When referenced component is unmounted or whenever the ref changes, the old ref will be called with
null
argument.