ReactJS Refs

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:-

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:-

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.

Recommended:-  ReactJS Component Lifecycle

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.

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:-

ReactJS Refs

In this tutorial we have learn about the ReactJS Refs and its application with practical example. I hope you will like this tutorial.