Forwarding Refs in React

Pranay Chauhan
Last Updated: May 13, 2022

Introduction

The component-based architecture of React allows us to have a hierarchical structure of components with parent and child components.

In the typical React dataflow, props are the only way that parent components interact with their children. 

To modify a child, you re-render it with new props. 

However, there are a few cases where you need to change a child outside of the typical data flow imperatively. 

The child to be modified could be an instance of a React component or a DOM element. For both of these cases, React provides an escape hatch to this with the help of refs.

Shocked GIF by The Tonight Show Starring Jimmy Fallon

So basically, Refs provide a way to access DOM nodes or React elements created in the render method.

We are going to learn about forwarding refs. Let us see ahead what are forwarding refs in react.

What are forwarding refs?

For a brief understanding, Ref forwarding is a technique for automatically passing a ref through a component to one of its children. 

Forwarding refs is typically not necessary for most components in the application. However, it can be helpful for some kinds of components, especially in reusable component libraries.

This concept can be best understood with an example so let's dive right into the code and then go over how it works.

How to Implement forwarding refs?

Consider an application where what we want to achieve is when we click on the button, and the parent component, the input in the child component should receive focus. However, we will use the forwarding ref technique to allow the parent component to reference the native input element directly.
 

Before forwarding refs

For this example, To reach the stage as shown in the above image, we will have to create two files—namely, FRInput.js and FRParentInput.js in the components folder.

FRInput.js

This is a functional component that simply returns an input field.

 

import React from "react";

function FRInput() {
  return (
    <div>
      <input type="text" />
    </div>
  );
}

export default FRInput;

 

FRParentInput.js

FRParentInput is a class component that uses the FRInput component and a button.

import React, { Component } from "react";
import FRInput from "./FRInput";

class FRParentInput extends Component {
  render() {
    return (
      <div>
        <FRInput ref={this.inputRef} />
        <button>Focus Input</button>
      </div>
    );
  }
}

export default FRParentInput;

 

App.js

From the App component, we will call the FRParentInput component.

import React from "react";
import "./App.css";
import FRParentInput from "./components/FRParentInput";

function App() {
  return (
    <div classname="App">
      <FRParentInput />
    </div>
  );
}

export default App;

 

Output

 

After using Forwarding refs

Step1: Create a ref in the parent component.

Step2: Attach the ref to the child component using the ref attribute, so FRInput ref is equal to this.inputRef.

FRParentInput.js

 

import React, { Component } from "react";
import FRInput from "./FRInput";

class FRParentInput extends Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  clickHandler = () => {
    this.inputRef.current.focus();
  };

  render() {
    return (
      <div>
        <FRInput ref={this.inputRef} />
        <button onClick={this.clickHandler}>Focus Input</button>
      </div>
    );
  }
}

export default FRParentInput;

 

Step3: we need to forward this ref to the input element in the child component, and ref forwarding can be achieved using the forwardRef method from the react library.

FRInput.js

In FRInput.js, which is our child component, we will modify how we create the functional component.

The new way to define the functional component is to simply replace the traditional function with an arrow function. You can see that we have not changed any functionality. We have simply rewritten the functional component using arrow functions.

 

import React from "react";

const FRInput = React.forwardRef((props, ref) => {
  return (
    <div>
      <input type="text" ref={ref} />
    </div>
  );
});

export default FRInput;

 

For forwarding refs, we use the default forwardRef method, which takes in a component as a  parameter, so we simply place the arrow function into the argument of this method. 

We know that every functional component receives props as its parameter but let me tell you, when a component is passed as a parameter to the create ref method, it gets the ref attribute as its second parameter. We can use this ref parameter and pass it to the ref attribute on the native input element.

This ref parameter will point to the value of the ref attribute from the parent component, or in other words, the ref is being forwarded from the parent component to the native input element.

The App.js file will stay the same as above. After doing all the changes, we see that in the browser, when we click on the “Focus input” button, the input field is getting focussed with the help of the forwarding refs technique.

Output

[crop output image]

Other uses of forwarding refs

Some of the application based uses of forwarding refs are:

  1. Forwarding ref using higher-order components.
  2. To display a custom name in the devtools.

Frequently Asked Questions (FAQs)

What are forwarding refs?

Ref forwarding is a technique for automatically passing a ref through a component to one of its children. 

Which method is used for forwarding refs in react?

We use forwardRef method in react to implement the forwarding refs.

What are the parameters of the component that creates the forwardRef method?

The functional component that creates the forwardRef method has two parameters, namely, props and ref.

Key Takeaways

We learned about the concept of forwarding refs in react. This is an advanced concept of forwarding refs in React that allows us to automatically pass a ref through a component to any of its children. This article also explained what are the uses for forwarding refs in React specifically. We also learned about the implementation of forwarding refs in React.

Apart from this, you can also expand your knowledge by referring to these articles on Javascript and React.

For more information about the react framework for frontend development, get into the entire Frontend web development course.

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think