Foward Ref : an underrated Hook in react
In React, the forwardRef
function is used to forward a ref
from a child component to a DOM element or a component that is deeper in the component tree. This is particularly useful when you are working with higher-order components
Here’s a simple explanation of how forwardRef
works:
- Creating a child component with a forwarded ref: First, you define a child component using
React.forwardRef
. This component takes aprops
object and aref
as parameters. Inside the component, you can use theref
in any way you need
2. Using the child component in a parent component: Now, you can use this ChildComponent
in a parent component and pass a ref
to it. The ref
can then be forwarded to the underlying DOM element.
In this example, the inputRef
is created using useRef
, and then it is passed as a ref
to the ChildComponent
. The ChildComponent
uses React.forwardRef
to forward the ref
to the underlying input
element.
Now, you can use inputRef.current
to interact with the DOM element inside ChildComponent
from the ParentComponent