Home > Web Front-end > JS Tutorial > How Can I Call Child Component Methods from a Parent Component in React?

How Can I Call Child Component Methods from a Parent Component in React?

Patricia Arquette
Release: 2024-12-23 15:37:12
Original
322 people have browsed it

How Can I Call Child Component Methods from a Parent Component in React?

Calling Child Methods from the Parent Component

In React, communication between components is typically achieved through props (properties) and events, but it is possible to access and invoke child component methods from the parent component using references.

Method Invocation Using Refs

  1. Wrap Child Component in forwardRef: To access the child component instance, wrap it in forwardRef. This allows React to pass the ref as the second argument to the component.
  2. Initialize Child Instance Ref: In the parent component, create a ref using useRef(). This will store the reference to the child component instance.
  3. Assign Ref to Child: Pass the ref to the child component using the ref prop. This assigns the child component instance to the parent component's ref.
  4. Expose Child Methods: Within the child component, use useImperativeHandle to return an object containing the methods you want to expose to the parent.

Example with Hooks

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>
  );
};

ReactDOM.render(<Parent />, document.getElementById('root'));
Copy after login

In this example, getAlert() is a method exposed by the Child component that can be invoked from the Parent component by accessing the current property of the childRef. Note that invoking child methods directly from the parent is not recommended and should be avoided in favor of proper component communication patterns.

The above is the detailed content of How Can I Call Child Component Methods from a Parent Component in React?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template