Working example of React Ref api

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)

  1. Ref creation 
     //creating Ref
      newInputItem = React.createRef();
  2. Adding Ref to element
    //using the Ref
      handleClick = () =>{
        this.newInputItem.current.focus();
      }
    <input type="text" 
                onChange={ update }
                ref={this.newInputItem} />
  3. 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>
    )
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *