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,

const Wrapper = cb => {
  return (res, triggerClickAnalytics) => (
    <RenderItem
      res={res}
      triggerClickAnalytics={triggerClickAnalytics}
      addFunc={cb}
    />
  );
};

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

const RenderItem = ({ 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

class Parent extends React.Component {
sayHello(name) => {
      console.log("Hello " + name)
}
render() {
        return <Child1 parentCallback = {this.sayHello}/>
    }
}

and then call it from the child component

class Child1 extends React.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"