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

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

5 days ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

7 days ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago

Top 10 Tips to Hire Shopify Developers

As the world of eCommerce continues to thrive, Shopify has become one of the most…

1 week ago

Managing Browser Events and Navigation in Shopify Remix: useBeforeUnload, useHref, and useLocation Hooks

Shopify Remix is an innovative framework that provides a streamlined experience for building fast, dynamic,…

1 week ago

Ultimate Guide to Hiring a Top Shopify Development Agency

Building a successful eCommerce store requires expertise, and for many businesses, Shopify has become the…

2 weeks ago