How to call child method from parent with React?

Sometimes, we want to call child method from parent with React.

In this article, we’ll look at how to call child method from parent with React.

How to call child method from parent with React?

To call child method from parent with React, we pass a ref to the child and assign the ref’s vale to the child’s function.

For instance, we write

const { forwardRef, useRef, useImperativeHandle } = React;

const Child = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    getAlert() {
      alert("getAlert from Child");
    },
  }));

  return <h1>Hi</h1>;
});

const Parent = () => {
  const childRef = useRef();

  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.getAlert()}>Click</button>
    </div>
  );
}

to create the Child component bwith the forwardRef function.

We call useImperativeHandle with the ref parameter so we can assign the function the 2nd argument to the ref.

Then in Parent, we create the ref with useRef and then pass it to the Child via the ref prop.

And then we can call childRef.current.getAlert in the onClick handler to show the alert.