ReactJS

How to Use forwardRef in ReactJS?

Hello ReactJS Friends,

In today’s blog, we will learn about forwardRef in ReactJS. First, let’s understand What is forwardRef in React, and then we will move on to its usage.

What is forwardRef in React?

In React, the forwardRef function is a built-in feature that allows you to pass a ref through a component to one of its children. It is typically used in higher-order components (HOCs) or when creating reusable components.

When you create a component using forwardRef, you can forward the ref attribute from the parent component to a specific element or component within the child component. This enables you to access the underlying DOM element or component instance directly.

Call forwardRef() to let your component receive a ref and forward it to a child component: 

import { forwardRef } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
    // ...
});

Parameters 

Render: The render function for your component. React calls this function with the props and ref that your component received from its parent. The JSX you return will be the output of your component.

Returns 

forwardRef returns a React component that you can render in JSX. Unlike React components, defined as plain functions, a component returned by forwardRef is also able to receive a ref prop.

Caveats 

In Strict Mode, React will call your render function twice in order to help you find accidental impurities. This is development-only behavior and does not affect production. If your render function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.

render function 

const MyInput = forwardRef(function MyInput(props, ref) {
    return (
        <label>
            {props.label}
            <input ref={ref} />
        </label>
    );
});

Parameters 

  • Props: The props passed by the parent component.
  • Ref: The ref attribute passed by the parent component. The ref can be an object or a function. If the parent component has not passed a ref, it will be null. You should either pass the ref you receive to another component, or pass it to useImperativeHandle.

Returns

forwardRef returns a React component that you can render in JSX. Unlike React components defined as plain functions, the component returned by forwardRef is able to take a ref prop.

Usage of forwardRef in React

By default, each component’s DOM nodes are private. However, sometimes it’s useful to expose a DOM node to the parent—for example, to allow focusing it. To opt in, wrap your component definition into forwardRef():

const MyInput = forwardRef(function MyInput(props, ref) {
    const { label, ...otherProps } = props;
    return (
        <label>
            {label}
            <input {...otherProps} />
        </label>
    );
});

You will receive a ref as the second argument after props. Pass it to the DOM node that you want to expose:

import { forwardRef } from 'react';
const MyInput = forwardRef(function MyInput(props, ref) {
    const { label, ...otherProps } = props;
    return (
        <label>
            {label}
            <input {...otherProps} ref={ref} />
        </label>
    );
});

This lets the parent Form component access the <input> DOM node exposed by MyInput:

function Form() {
    const ref = useRef(null);
    function handleClick() {
        ref.current.focus();
    }
    return (
        <form>
            <MyInput label="Enter your name:" ref={ref} />
            <button type="button" onClick={handleClick}>
                Edit
            </button>
        </form>
    );
}

This Form component passes a ref to MyInput. The MyInput component forwards that ref to the <input> browser tag. As a result, the Form component can access that <input> DOM node and call focus() on it.

Keep in mind that exposing a ref to the DOM node inside your component makes it harder to change your component’s internals later. You will typically expose DOM nodes from reusable low-level components like buttons or text inputs, but you won’t do it for application-level components like an avatar or a comment.

Conclusion:

React’s forwardRef is a powerful tool allowing you to traverse the component hierarchy and access specific elements or instances. By understanding the intricacies of forwardRef and its various applications, you can unlock new possibilities for manipulating the DOM, interacting with child components, and creating reusable components. With this comprehensive guide, you can effectively leverage forwardRef in your React projects.

To learn more about ReactJS, get in touch with experienced ReactJS developer.

Happy Coding!

Click to rate this post!
[Total: 1 Average: 5]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer 🏅 with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket 🏏.

Recent Posts

Boost Your SEM Game: Unveiling the Top 10 Tools for Marketers in 2024

Business survival in today’s digital world has become extremely difficult. Using traditional marketing techniques is…

11 hours ago

Five Essential Payroll Compliance Tips for eCommerce Startups

Are you setting up a payroll system for your eCommerce startup? Ensuring compliance with myriad…

1 day ago

Optimizing Laravel Blade: Unlocking Advanced Fetcher Techniques

In the expansive universe of Laravel development, Blade serves as the stellar templating engine, propelling…

1 day ago

Magento 2: Add Quantity Increment and Decrement on Category Page

Hello Magento Friends, In this blog, we will discuss about adding quantity increment and decrement…

3 days ago

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

6 days ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

1 week ago