I have two components.
I was trying to call child\'s method from Parent, I tried this way but couldn\
Another way of triggering a child function from parent is to make use of the componentDidUpdate
function in child Component. I pass a prop triggerChildFunc
from Parent to Child, which initially is null
. The value changes to a function when the button is clicked and Child notice that change in componentDidUpdate
and calls its own internal function.
Since prop triggerChildFunc
changes to a function, we also get a callback to the Parent. If Parent don't need to know when the function is called the value triggerChildFunc
could for example change from null
to true
instead.
const { Component } = React;
const { render } = ReactDOM;
class Parent extends Component {
state = {
triggerFunc: null
}
render() {
return (
);
}
}
class Child extends Component {
componentDidUpdate(prevProps) {
if (this.props.triggerChildFunc !== prevProps.triggerChildFunc) {
this.onParentTrigger();
}
}
onParentTrigger() {
alert('parent triggered me');
// Let's call the passed variable from parent if it's a function
if (this.props.triggerChildFunc && {}.toString.call(this.props.triggerChildFunc) === '[object Function]') {
this.props.triggerChildFunc();
}
}
render() {
return (
Hello
);
}
}
render(
,
document.getElementById('app')
);
CodePen: https://codepen.io/calsal/pen/NWPxbJv?editors=1010