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. Than
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 Child Component
;
});
Call the exposed function from the parent with the ref.
const Parent = () => {
const childRef = useRef();
return (
);
};