What is React Ref?
Its another way of communicating with react components apart from “state” and “props” (Ref = creating reference of element). We need it to access the element node, to perform special type of events like “focusing a input element”, text selection.
How React Ref works?
After React 16.3, it came in the form of CreateRef api (before that it was used as callback ref, which is still supported)
- Ref creationÂ
//creating Ref newInputItem = React.createRef();
- Adding Ref to element
//using the Ref handleClick = () =>{ this.newInputItem.current.focus(); }
<input type="text" onChange={ update } ref={this.newInputItem} />
- Using that reference
//using the Ref handleClick = () =>{ this.newInputItem.current.focus(); }
Example:- We need to set focus inside the text box, when we click a “FocusMe” button.
class Widget extends Component { //creating Ref newInputItem = React.createRef(); //using the Ref handleClick = () =>{ this.newInputItem.current.focus(); } render(){ const { update} = this.props; return ( <React.Fragment> <button onClick={this.handleClick}>FocusMe</button> {/* adding Ref */} <input type="text" onChange={ update } ref={this.newInputItem} /> </React.Fragment> ) } }