The following line:
The function child A called from parent now executes a function in
component B.
is strange/ and a no-go area with react: A parent cannot (should not) directly call a function inside a child component.
A parent can (should) pass a prop to the child, and then the child can initiate its own function.
If I understand correctly, you want to execute the function inside child B to execute when a) component A is clicked AND b) component B is mounted
You can achieve this as follows:
- add a state parameter inside parent, e.g.
this.setState(childAClicked: true)
, most likely inside the callback function inside the parent, called by child A.
- pass this parameter to child B, e.g.
<ChildB clickedA = {this.state.childAClicked} />
- inside child B, add a
componentDidMount()
lifecycle method, which checks this.props.clickedA
, and if true, executes your function inside child B
- if you want to execute the function also after updates to child B, add the same check inside a
componentDidUpdate()
lifecycle method
If you want to execute the function ONLY inside one of the components B, C, D, based on some other parameter, you add this parameter as well to your parent's state, and pass it to other B,C and D components too.