Create ref
Use React.createRef() to create refs and get the React element through the ref attribute.
class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return <div ref={this.myRef} />; } }
Visit Refs
When a ref attribute is passed to an element in the render function, the current attribute in ref can be used to access the reference of the node.
const node = this.myRef.current;
Demo
class CustomTextInput extends React.Component { constructor(props) { super(props); // Create ref to store textInput DOM elements this.textInput = React.createRef(); this.focusTextInput = this.focusTextInput.bind(this); } focusTextInput() { // Using native API directly to focus text input box // Note: get the DOM node through "current" this.textInput.current.focus(); } render() { // Tell React that we want to associate < input > ref to the 'textInput' created in the constructor return ( <div> <input type="text" ref={this.textInput} /> <input type="button" value="Focus the text input" onClick={this.focusTextInput} /> </div> ); } }
The ref attribute cannot be used on functional components because they have no instances
function MyFunctionalComponent() { return <input />; } class Parent extends React.Component { constructor(props) { super(props); this.textInput = React.createRef(); } render() { // This will not work! return ( <MyFunctionalComponent ref={this.textInput} /> ); } }
Callback Refs
This form is widely used in practice
class Parent extends React.Component { render() { return ( <input inputRef={el => this.inputElement = el} /> ); } }
Old API: Refs of String type
If you have used React before, you may have known the ref attribute of string type in the previous API, such as "textInput". You can access the DOM node through this.refs.textInput. We don't recommend using it because refs of type string Existing problems . It is obsolete and may be removed in future releases. If you are still using this.refs.textInput to access refs, we suggest using callback instead.