How to create refs in ReactJS?


In ReactJS, refs are used to referring any node of the document. Generally, we can pass the props to children elements to interact with children from the parent’s state. Still, sometimes the child component is out of the typical dataflow of components. For example, we have four components, and dataflow is second is a child of the first, third is a child of the second, and fourth is a child of the third component. To interact with the fourth component from the first component, passing props from every component is not good practice. So, we can use refs to interact directly fourth component from the first component.

In this tutorial, we will learn two ways to refer to the DOM elements using refs.

Creating the refs via the React.createRef() and useRef() hooks

In ReactJs, the first way to create refs is using React.CreateRef() for class components and useRef() hooks for the function components. After creating the ref variable in the component, we can assign it as a value of the ref attribute of any HTML element. So, it can contain the reference of the element.

Syntax

Users can follow the syntax below to use React.Createref() to create a ref in the class components.

this.InputElement = React.createRef();
<input type = "text" ref = {this.InputElement} id = "text" />

In the above syntax, we have created the InputElement ref and assigned it to the input.

Users can follow the syntax below to use the useRef() hooks to create ref in functional components.

const input = useRef(null);
<input type = "text" ref = {input} /> 

In the above syntax, we have created the input ref using useRef() and referred to the text input.

Example

In the example below, we have created the class component containing the text input. In the constructor of the class component, we have created the InputElement ref and state object.

After that, when the user clicks the button, it executes the getInputValue() method, which uses the refs to get value of the input.

import React from "react";
class App extends React.Component {
   constructor(props) {
      super(props);
      
      //creating refs to access input elements
      this.InputElement = React.createRef();
      this.getInputValue = this.getInputValue.bind(this);
      this.state = {
         text: "",
      };
   }
   
   // method to get texts from the input
      getInputValue(e) {
         e.preventDefault();
         this.setState({ text: this.InputElement.current.value });
      }
      render() {
         return (
            <div>
               {/* use the ref attribute */}
               <h2> Using the refs with class components </h2>
               <p>Enter some text below:</p>
               <input type = "text" ref = {this.InputElement} id = "text" /> 
               <br></br>
               <div> The submitted value is {this.state.text}. </div>
               <button onClick = {this.getInputValue}> Click here </button>
            </div>
         );
      }
}
export default App;

Output

Example

In the example below, we have used the refs with functional components. Here, we have used the userRef() hooks to create an input ref. Afterwards, we used the ref attribute with the HTML input and referred input ref to it.

Next, we use the ref to get the value of the input, as in the first example.

import { useState } from "react";
import { useRef } from "react";
export default function App() {
   const input = useRef(null);
   const [value, setValue] = useState(""); 
   function handleClick() {
      let value = input.current.value;
      setValue(value);
   }
   return (
      <div>
         <h2>
            {" "}
            Using the refs with functional components
         </h2>
         <input type = "text" ref = {input} />
         <br></br>
         <div> The value you have entered in the text input is {value}.</div>
         <input type = "button" value = "Submit Text" onClick = {handleClick} />
      </div>
   );
} 

Output

Creating the refs via a callback function

As a developer, if you want to write more readable and clear code while creating the refs, you should use the callback refs. The ‘refs’ attribute of the element takes a callback function as a value rather than a ref variable. After that, we can get the element as a first parameter of the callback function, and we can use it to set focus on the element or perform other operations.

Syntax

Users can follow the syntax below to create refs via callback functions.

input type = "text" ref = {(ele) => {
   this.input = ele;
};
} /> 

In the above syntax, input is a variable declared in the component, and ele refers to the input element itself.

Example

In the example below, we can create the refs using callback functions. First, we created the input variable in the constructor and initialized it with a null value. After that, we passed the setRef callback function as a value of the refs attribute of the input element.

The ‘refs’ attribute invokes the setRef() function, which stores the reference of the input element to the input variable, and we access the value of the input variable in the getTextInput() method.

import React from "react";
class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         text: "",
      };
      this.input = null;
      this.setRef = (ele) => {
         this.input = ele;
      };
      this.getTextValue = () => {
         this.setState({ text: this.input.value });
      };
   }
   render() {
      return (
         <div>
            {/* use the ref attribute */}
            <h2> Using the callback refs in ReactJS </h2>
            <input type = "text" ref = {this.setRef} id = "text" />
            <br></br>
            <div> The submitted value is {this.state.text}. </div>
            <button onClick = {this.getTextValue}> Click here </button>
         </div>
      );
   }
}
export default App; 

Output

Using the refs to interact with child components

Refs were introduced to interact with the parent component from the child component. Here, we will create ref in the child and parent components and interact with the child component’s elements via the parent component.

Syntax

Users can follow the syntax below to interact with child components from parents using refs.

// access refs of the child component

this.childClassRef.current.testRef.current.focus();
return <Child ref={this.childClassRef} />; 

In the above syntax, we have passed the ref to the child component and accessed the ref of the child component.

Example

Filename – App.js

In the App.js file, we have imported the child component and passed the ref as a prop. The childClassRef refers to the child component. Also, users can see how we accessed the child component’s ref in the componentDidMount() method.

The testRef ref is declared in the child component, and in such a way, we can access the ref of the child component from the parent component.

import React from "react";
import Child from "./Child";
class App extends React.Component {
   constructor(props) {
      super(props);
      this.childClassRef = React.createRef();
   }
   componentDidMount() {
      this.childClassRef.current.testRef.current.focus();
   } 
   render() {
      return <Child ref = {this.childClassRef} />;
   }
}
export default App;

Filename – Child.js

In the Child.js file, we have created the testRef ref using the React.createRef() and referred to the input element.

import React from "react";
import { Component } from "react";
class Child extends Component {
   constructor(props) {
      super(props);
      this.testRef = React.createRef();
   }
   render() {
      return (
         <div>
            <h3> This is a child component. </h3>
            <input type = "text" ref = {this.testRef} />
         </div>
      );
   }
}
export default Child;

Output

In the above output, users can observe that whenever we refresh the page, the application focuses on the child component's input element from the parent component.

Updated on: 28-Feb-2023

201 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements