I have requirement to call child component method from parent component in reactjs. I have tried using refs but not able to do it. Can anyone please suggest any solution. Thanks.
If using React Hooks, you can make use of useRef and useImperativeHandle hooks.
In the child component, add the functions in the hook.
const Child = forwardRef((props, ref) => {
const printSomething = () =>{
console.log('printing from child function')
}
useImperativeHandle(ref, () => ({
printSomething: printSomething
}));
return <h1>Child Component</h1>;
});
Call the exposed function from the parent with the ref.
const Parent = () => {
const childRef = useRef();
return (
<div>
<Child ref={childRef} />
<button onClick={() => childRef.current.printSomething()}>Click</button>
</div>
);
};
Don't :)
Hoist the function to the parent and pass data down as props. You can pass the same function down, in case the child needs to call it also.
https://facebook.github.io/react/docs/lifting-state-up.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With