There are several use cases of React.forwardRef. One of its main features is the ability to pass the data from parent components to the child components through the props.
Using the React.forwardRef, we can pass a ref to child component so that the parent component can access its internal state and methods.
This is very useful when we need to manipulate the child component, such as scrolling to a certain position or triggering an animation.
Following is an example of how to use React.forwardRef?
import React, { useRef, useImperativeHandle, forwardRef } from 'react';
const MyComponent = forwardRef((props, ref) => {
const myRef = useRef(null);
useImperativeHandle(ref, () => ({
scrollToTop() {
myRef.current.scrollTop = 0;
}
}));
return (
<div ref={myRef}>
{/* your component code here */}
</div>
);
});
In the above example, we defined the MyComponent
component that accepts a ref using the forwardRef
. We then create a myRef
using the useRef
hook, and pass to the div
element using the ref
prop.
Inside the useImperativeHandle
hook, we define a method called scrollToTop
that sets the scrollTop
property of the myRef.current
element to 0. Parent component can access this method through the ref.
To access this component from the parent component, we create a ref using the useRef
hook and pass it to the child component i.e. MyComponent.
Following is the example:
import React, { useRef } from 'react';
function ParentComponent() {
const myRef = useRef(null);
const handleClick = () => {
myRef.current.scrollToTop();
};
return (
<div>
<MyComponent ref={myRef} />
<button onClick={handleClick}>Scroll to top</button>
</div>
);
}