user3840147
user3840147

Reputation: 107

Is there any way to know if a child component has mounted in React

I'm wondering if there is any possibility to find out from this.props.children if a specific child has been mounted?

The reason why I am asking this is that I would like to create a wrapper component that would deal with some sort of async rendering (specifically for react-native) and render children one after another. Just wondering how that could be accomplished using a simple wrapper component.

Any help would be appreciated.

Edit:

Just to describe the expected result more. Let's say I have a render method that has something like

<View>
  <Text>I'm a string</Text>
  <View>
    <Image />
    <Image />
    <Image />
    <Image />
  </View>
  <View>
    <View />
    <View />
  </View>
</View>

I would like to create a wrapper that would asynchronously render each of the blocks and have something like

<ASyncRenderWrapper>
  <Text>I'm a string</Text>
  <View>
    <Image />
    <Image />
    <Image />
    <Image />
  </View>
  <View>
    <View />
    <View />
  </View>
</ASyncRenderWrapper>

Now instead of assigning a ref to each child I would like to go over this.props.children and render them one by one, but to render the next child I would have to know that the previous has mounted.

Some pseudocode to illustrate what I think the wrapper component should look like or do

state = {
  childRenderList: Array.apply(null, Array(props.children.length)).map(() => false),
}
refCounter = 0
componentDidMount() {
  this.startAsyncRender()
}
startAsyncRender = () => {

  if (children[refCounter]) {

    //      Somehow figure out if the previous child has been mounted to know if this one can be allowed to mount
    //      Alternativly I guess I could just skip a render cycle with setTimeout

    childRenderList = childRenderList[refCounter] = true;
    this.setState({ childRenderList: childRenderList });

    if (children[refCounter + 1]) {
      this.startAsyncRender();
      this.refCounter++
    }
  }
}
canRender = (index) => {
  return childRenderList[index];
}
return (
  { children.map((Child, index) => canRender(index) && <Child />) }
)

Upvotes: 0

Views: 2423

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

In your child component:

state = {
  domMounted: false //initial state
}

componentDidMount() {
  this.setState({domMounted: true})
}

<Child ref={(childRef) => {this.childRef = childRef} />

In your parent component:

this.childRef.state.domMounted

Upvotes: 3

Related Questions