Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call child component method from parent component in reactjs

Tags:

reactjs

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.

like image 736
Rajan Gupta Avatar asked Jun 21 '17 09:06

Rajan Gupta


2 Answers

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>
  );
};
like image 122
Sarat Chandra Avatar answered Nov 05 '22 18:11

Sarat Chandra


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

like image 27
Garry Taylor Avatar answered Nov 05 '22 18:11

Garry Taylor