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;_x000D_
const { render } = ReactDOM;_x000D_
_x000D_
class Parent extends Component {_x000D_
state = {_x000D_
triggerFunc: null_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
<Child triggerChildFunc={this.state.triggerFunc} />_x000D_
<button onClick={() => {_x000D_
this.setState({ triggerFunc: () => alert('Callback in parent')})_x000D_
}}>Click_x000D_
</button>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
class Child extends Component {_x000D_
componentDidUpdate(prevProps) {_x000D_
if (this.props.triggerChildFunc !== prevProps.triggerChildFunc) {_x000D_
this.onParentTrigger();_x000D_
}_x000D_
}_x000D_
_x000D_
onParentTrigger() {_x000D_
alert('parent triggered me');_x000D_
_x000D_
// Let's call the passed variable from parent if it's a function_x000D_
if (this.props.triggerChildFunc && {}.toString.call(this.props.triggerChildFunc) === '[object Function]') {_x000D_
this.props.triggerChildFunc();_x000D_
}_x000D_
}_x000D_
_x000D_
render() {_x000D_
return (_x000D_
<h1>Hello</h1>_x000D_
);_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
render(_x000D_
<Parent />,_x000D_
document.getElementById('app')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>_x000D_
<div id='app'></div>
_x000D_