Refs

15 Apr 2024 . react .

It is an attribute which helps to store a reference to a particular React element or component returned by render(). They come in handy when we need DOM measurements or to add methods to the components.

class ReferenceDemo extends React.Component{
   display() {
         const name = this.inputDemo.value;
         document.getElementById('disp').innerHTML = name;
     }

	render() {
    return(          
			<div>
            Name: <input type="text" ref={input => this.inputDemo = input} />
            <button name="Click" onClick={this.display}>Click</button>            
		        <h2>Hello <span id="disp"></span> !!!</h2>
      </div>
    );
   }
 }
  • When you need to manage focus, select text or media playback
  • To trigger imperative animations
  • Integrate with third-party DOM libraries