React Refs
React supports a very special property called Ref that you can use to bind to any component rendered by render().
This special property allows you to reference the corresponding backing instance returned by render(). This ensures that you always get the correct instance at any time.
Usage
Bind a ref attribute to the return value of render():
<input ref="myInput" />
In other code, retrieve the backing instance via this.refs:
var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();
Complete Example
You can access the current React component using this or get a reference to the component using ref, as shown in the example below:
React Example
class MyComponent extends React.Component {
handleClick() {
// Use the native DOM API to focus
this.refs.myInput.focus();
}
render() {
// When the component is inserted into the DOM, the ref attribute adds a reference to this.refs
return (
<div>
<input type="text" ref="myInput" />
<input
type="button"
value="Click me to focus the input box"
onClick={this.handleClick.bind(this)}
/>
</div>
);
}
}
ReactDOM.render(
<MyComponent />,
document.getElementById('example')
);
In the example, we obtain a reference to the backing instance of the input box and focus it when the button is clicked.
We can also use the getDOMNode() method to get the DOM element.