2

Here is the component hierarchy I have.

<Parent>
    <Child1>
        <Child2>
        </Child2>
    </Child1>
<Parent>

In Child2 component, there is a function called handlePatch(). I need to call it from Parent component but not sure how to do it. What is the best approach for this?

Thanks.

Patrick Blind
  • 399
  • 1
  • 4
  • 15

1 Answers1

1

you could pass on a ref of the Child component to the Parent as props and access that to call the function like

class App extends React.Component {
    constructor() {
       super();
       this.child = null;
    }
    render() {
        return (
             <Parent childRef={this.child}>
                <Child ref={(ref) => this.child = ref}/>
             <Parent>
        )
    }
}

class Parent extends React.Component {
    myfunc = () => {
        //call child function
        this.props.childRef.handlePatch();
    }
}

However you can try to avoid it by restructuring your code a little better and directly calling the function in Child from the container of Parent component.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400