React refs - Tuong-Nguyen/JavaScript-Structure GitHub Wiki

The ref returned from ReactDOM.render

  • ReactDOM.render() will return a reference to our component's backing instance
  • For stateless components, it returns null

The ref String Attribute

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 in componentWillMount, in this state, the element have not been rendered yet.

The ref Callback Attribute

  • 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.