Tiberiu Maxim Tiberiu Maxim - 1 year ago 118
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:


The render method of
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
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
would be triggered before CDM of any

I could pass down a method from top to each
that would be called at CDM. On GrandParent I would wait for all
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
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.

Is componentDidMount of parent called after all componentDidMount of children?

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download