Skip to content Skip to sidebar Skip to footer

How To Call Function In Parent Component From The Child Component

I have a function called addFunc in my main Class. This class calls the RenderItem function to display a list of items. Each item has an onClick that should execute the addFunc fun

Solution 1:

You can wrap RenderItem component with another component and then render it,

constWrapper = cb => {
  return(res, triggerClickAnalytics) => (
    <RenderItemres={res}triggerClickAnalytics={triggerClickAnalytics}addFunc={cb}
    />
  );
};

and renderItem of ReactiveList would be: renderItem={Wrapper(this.addFunc)} then RenderItem component would be

constRenderItem = ({ res, triggerClickAnalytics, addFunc }) => {
...

see sandbox: https://codesandbox.io/s/autumn-paper-337qz?fontsize=14&hidenavigation=1&theme=dark

Solution 2:

You can pass a callback function defined in the parent as a prop to the child component

classParentextendsReact.Component {
sayHello(name) => {
      console.log("Hello " + name)
}
render() {
        return<Child1parentCallback = {this.sayHello}/>
    }
}

and then call it from the child component

classChild1extendsReact.Component{
componentDidMount() {
   this.props.parentCallback("Foo")
}
render() { 
    return<span>child component</span>
    }
};

Post a Comment for "How To Call Function In Parent Component From The Child Component"