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!