In this tutorial you will learn about the ReactJS Refs and its application with practical example.
ReactJS Refs
In React, refs are similar to keys and can be added to an element as a attribute. Setting a refs to an element returns a reference to the actual element. The refs attribute is used to access and manipulate the DOM elements such as managing focus, text selection, or reset value etc. The refs can be used as in callbacks. However, overuse of the refs should be avoided.
Creating Refs
In React, a refs is created using React.createRef()
function and then can be assigned to a React elements using the ref
attribute.
Example:-
1 2 3 4 5 6 7 8 9 |
class HelloComponent extends React.Component { constructor(props) { super(props); this.helloRef = React.createRef(); } render() { return <div ref={this.helloRef} />; } } |
Accessing Refs
In React, when a ref is assigned to HTML element inside render
method, a reference to the node is accessible via current
attribute of the ref.
Example:-
1 |
const helloNode = this.helloRef.current; |
Refs current
Property
The refs behave differently as per the type of the element it is with. When a ref is assigned to HTML element inside render
method, the ref
object created in the constructor returns the underlying DOM element as its current
property. While, when the ref
attribute used with a custom class component, the ref
object returns the current instance of the component as its current
property.
Note:- The ref
attribute can not be used with functional components as they don’t have instances.
Example:-
Step 1:- Let’s open src/App.js, delete the existing code and put the following code in it and save it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import React, { Component } from 'react'; class App extends React.Component { constructor(props) { super(props); this.txtReff = React.createRef(); this.focusToTxt= this.focusToTxt.bind(this); } focusToTxt() { // focus to text input this.txtReff.current.focus(); } render() { return ( <div> <h1>W3Adda - ReactJS Refs</h1> <input type="text" ref={this.txtReff} /> <input type="button" value="Set focus" onClick={this.focusToTxt} /> </div> ); } } export default App; |
Step 2:- Let’s open the terminal again, change directory to your project folder and type the following command in order to run the server.
1 |
npm start |
Step 3:- Now open the following URL in browser to view the output
http://localhost:3000
Step 4:- You will see the following screen.
Output:-