Tiberiu Maxim Tiberiu Maxim - 23 days ago 14
React JSX Question

React callback to scroll after all children are rendered

I need to execute a piece of code after all grandchildren of a Component are rendered to scroll to one of the grandchildren. The structure looks like this:

`<GrandParent>
<IntermediateParent>
<IntermediateParent2>
<GrandChild/>
<GrandChild/>
<GrandChild/>
<GrandChild/>
</IntermediateParent2>
</IntermediateParent>
</GrandParent>`


The render method of
GrandParent
looks like this:

render() {
if (!this.props.listOfGrandchildren) { // still loading data from server
return <div>LOADING...</div>
}

return <IntermediateParent grandchildren={this.props.listOfGrandchildren} />
}


It is clear that using
ComponentDidMount
will clearly not work because of the children being mounted at a later time, after the data is loaded from the server. In this case, CDM of
GrandParent
would be triggered before CDM of any
GrandChild


I could pass down a method from top to each
GrandChild
that would be called at CDM. On GrandParent I would wait for all
GrandChild
to call that method by using a counter and once the counter would be equal to the number of grandchildren I could call my piece of code that would scroll to the wanted grandchild, but this feels like a lot of hassle.

I want to load the
GrandParent
before the data comes down from the server, to render a placeholder/loading element.
I am looking for a more elegant method to solve this.

UPDATE:
Is componentDidMount of parent called after all componentDidMount of children?

I know why my
GrandChild
ren's CDM is triggered after CDM of
GrandParent
just looking to have a different behaviour

Answer

In the end the most neat solution was the following:

I set up ComponentDidMount on IntermediateParent (works with IntermediateParent2 as well) which calls an action creator that sets a flag loadedX = true.

Then, in GrandParent's ComponentWillReceiveProps wait for the loadedX prop to become true. When this happens, manually call the desired 'callback' function. I inject the loadedX prop to GrandParent using connect.

Hope this also helps someone else. If you need more details ask in comments. I can also come up with some code for a more real world example.