2

I have 3 components. One parent component and two child components (A,B). The first child component A has a button that triggers a parent components function. The parent has a switch either to display child component B or not. If the child component B shall be visible it becomes mounted. The function child A called from parent now executes a function in component B.

I tried to realise it by providing a ref attribute on child component B. But as it is not mounted for a good reason on init this.refs is empty. How can I achieve this without mounting all possible child components B (or later C,D,E) initially.

It is important that the onClick event in child A always triggers the referenced events.

Here is a quick draft:enter image description here

Can anybody give me a hint to solve my logical problem?

bdart
  • 745
  • 6
  • 18
  • i think a `componentWillReceiveProps` on each child (b-d) is the place to invest; ignore on a hidden one, do stuff on the shown one. you could also "cheat" with something like EventEmmiters or redux. – dandavis Apr 18 '16 at 19:50

1 Answers1

1

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.

wintvelt
  • 13,855
  • 3
  • 38
  • 43
  • Oh my god you are so right... I couldn't see the forest for the trees. Thx a lot – bdart Apr 18 '16 at 20:48
  • But what in a case when you click again the button? The value of clickedA in the B component is already set to true, so it doesn't change, so how do you capture the button was clicked? You'd have to swith it to false, but then the logic doesn't really make sense, right? – prk_001 Sep 28 '19 at 09:22