• It is a function provided by React to access the DOM element and the React element that you might have created on your own.
  • In React, a ref is a reference to a DOM element.
  • It can be immediately placed in a variable.
  • They are created with the help of useRef
  • This variable is then passed to a given React element (not a component) to get a reference to the underlying DOM element (that is, div, span, and so on).
  • Properties are now available on the element itself.
  • Refs are often referred to as an “escape hatch” to be able to work with a DOM element directly.
  • They allow us to do certain operations that can’t be done through React otherwise, such as clearing or focusing an input.

For Example,

// using refs

class App extends React.Component {

 constructor(){

  super();

  this.state = { sayings: ""};

 }

 update(e){

  this.setState({ sayings: this.refs.anything.value});

 }

 render(){

  return (

   <div>

    Welcome to Kaashiv <input type="text" ref="anything"

      onChange = {this.update.bind(this)}/>

   <br/>

   <em>{this.state.sayings}</em>

  </div>

  );

 }

}

 ReactDOM.render(< App />, document.getElementById('root'));

 

 Output:

Categorized in: