Working example of React Ref api – User friendly Tech help

n

What is React Ref?

n

n

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.

n

n

How React Ref works?

n

n

After React 16.3, it came in the form of CreateRef api (before that it was used as callback ref, which is still supported)

n

    n

  1. Ref creation n
     //creating Refn  newInputItem = React.createRef();
  2. n

  3. Adding Ref to elementn
    //using the Refn  handleClick = () =>{n    this.newInputItem.current.focus();n  }
  4. n

  5. Using that referencen
     //using the Refn  handleClick = () =>{n    this.newInputItem.current.focus();n  }
  6. n

n

n

Example:- We need to set focus inside the text box, when we click a “FocusMe” button.

n

n

class Widget extends Component {n  //creating Refn  newInputItem = React.createRef(); n  //using the Refn  handleClick = () =>{n    this.newInputItem.current.focus();n  }nn  render(){n    const { update} = this.props;n    return (n      n        FocusMen        {/* adding Ref */}n        n      n    )n  }n}
Was this article helpful?
YesNo

Similar Posts