In React, it's generally best practice to pass down functionality to children through props and to pass up notifications from children through events. However, there may be times when you need to expose an imperative method on a child component to be called from the parent component. In these cases, you can use refs.
To use refs in functional components, you'll need to use the forwardRef, useRef, and useImperativeHandle hooks from the React library.
First, you'll need to wrap your child component in the forwardRef function in order to access the ref object that is assigned using the ref prop. The ref is passed as the second parameter to the function component.
Next, you'll need to use the useImperativeHandle hook to extend the component instance with the imperative method you want to expose.
In the parent component, you'll need to use the useRef hook to get a reference to the child component, and then use this reference to call the child's method.
Here's an example of how to use refs to call a child method from a parent component in modern React:
const { forwardRef, useRef, useImperativeHandle } = React;
const Child = forwardRef((props, ref) => {
const childRef = useRef();
useImperativeHandle(ref, () => ({
getAlert() {
alert("You clicked the button!");
}
}));
return <h1>Child</h1>;
});
const Parent = () => {
const childRef = useRef();
return (
<div>
<Child ref={childRef} />
<button onClick={() => childRef.current.getAlert()}>Click</button>
</div>
);
};
ReactDOM.render(
<Parent />,
document.getElementById('root')
);
Please keep in mind that using refs in this way is an escape hatch, and usually indicates that a better design is available.
Top comments (0)