Skip to content
Related Articles

Related Articles

Improve Article

ReactJS | Refs

  • Last Updated : 08 Jan, 2021

Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all. They also provide us with good functionality as we can use callbacks with them. 

Example:  

Javascript




// without refs
class App extends React.Component {
  constructor(){
   super();
   this.state = { sayings: ""};
   }
  update(e){
   this.setState({ sayings: e.target.value});
  }
  render(){
   return (
    <div>
     Mukul Says <input type="text" onChange = {this.update.bind(this)}/>
    <br/>
    <em>{this.state.sayings}</em>
   </div>
  );
 }
}
ReactDOM.render(< App />, document.getElementById('root'));

Output: 



In the above example, we are making use of the target value of event e, for getting the value of what Mukul is saying. The above output can also be achieved by using the refs. 

Example:  

Javascript




// using refs
class App extends React.Component {
 constructor(){
  super();
  this.state = { sayings: ""};
 }
 update(e){
  this.setState({ sayings: this.refs.anything.value});
 }
 render(){
  return (
   <div>
    Mukul Says <input type="text" ref="anything"
      onChange = {this.update.bind(this)}/>
   <br/>
   <em>{this.state.sayings}</em>
  </div>
  );
 }
}
 ReactDOM.render(< App />, document.getElementById('root'));

Output: 
 

In the above we make use of refs provided by React, they can also be used to add callback functions inside them which is helpful in many cases. 

Example:  

Javascript




// callback used inside ref
class App extends React.Component {
  constructor(){
   super();
   this.state = { sayings: ""};
  }
  update(e){
   this.setState({ sayings: this.a.value});
  }
  render(){
   return (
    <div>
     Mukul Says <input type="text"
     ref={(call_back) => {this.a = call_back}} onChange =
     {this.update.bind(this)}/>
   <br/>
   <em>{this.state.sayings}</em>
   </div>
  );
 }
}
ReactDOM.render(< App />, document.getElementById('root'));

Output: 

When to use refs  

  • Helpful when using third party libraries.
  • Helpful in animations.

When not to use refs 

  • Should not be used with functional components because they don’t have instances.
  • Not to be used on things that can be done declaratively.

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :