Learning

What is forwardRef and how its helps in react?

Hello, lets quickly take a review on React forwardRef, what it in actual,

In React, the forwardRef function is a utility that allows you to pass a ref through a component to one of its children. It’s commonly used when you need to access the underlying DOM node or React component instance of a child component from the parent component.

When you create a component using functional components in React, you can use the useRef hook to create a ref object. This ref object can then be passed as a prop to child components. However, when you pass the ref as a prop to a child component, React does not automatically pass it down to the underlying DOM element or custom component. This is where forwardRef comes into play.

By using forwardRef, you can create a component that accepts a ref and forwards it to one of its children. Here’s an example:

const ChildComp = React.forwardRef((props, ref) => {
  // Use the ref object to access the underlying DOM node or component instance
  return <input ref={ref} />;
});

const ParentComp = () => {
  const inputRef = React.useRef(null);

  const handleClick = () => {
    // Access the input element using the ref
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  return (
    <div>
      <ChildComponent ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};

In the example above, the ChildComponent uses forwardRef to forward the ref prop to the <input> element. In the ParentComponent, a ref is created using the useRef hook and passed to ChildComponent using the ref prop. This allows the ParentComponent to access the input element and call the focus method when the button is clicked.

By using forwardRef, helps to bridge the gap between functional components and the imperative DOM or component operations that sometimes require direct access to child component element.

Note here we are accessing child’s component dom node not child component here as ref object, i.e can be consider as subtle difference to understand for our mind.

Hope this helps to clear out the basic concept behind using forwardRef in React.

Happy Learning!

admin

Recent Posts

The Ultimate Guide to Effective Meetings

In today’s fast-paced work environment, meetings are essential but can often feel unproductive. However, by…

2 months ago

From Mine to Market: How Gold Is Mined, Refined, and Sold in Shops

Gold is one of the most coveted precious metals in the world, adored for its…

3 months ago

The Historical Journey of Gold: From Ancient Civilizations to Modern Times

Gold, the shimmering metal synonymous with wealth, power, and beauty, has been deeply intertwined with…

3 months ago

How to Onboard an Intern in Small, Individual-Based Company

How to Onboard an Intern in a Small, Individual-Based Company Hiring an intern can be…

4 months ago