0

If I try to do document.querySelector for an element inside the React component inside componentDidMount, it seems like it does not guarantee it (componentDidMount) gets called after its on the DOM. The result is it cannot find the element

Is there an event I should used instead if I want to access the DOM? After its attached to the DOM?

As a workaround, I used setTimeout is there a better way?

Jiew Meng
  • 84,767
  • 185
  • 495
  • 805

1 Answers1

1

Another approach is that in your componentDidMount method set some state change. it makes an update on your component and call render method again with absolute mounted status.

like this:

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

componentWillUpdate(nextProps, nextState){
  if(nextState.isMounted){
     // do something for your query selecting
  }
}

componentWillUnmount(){
  // do something else if you want
}
Emad Emami
  • 6,089
  • 3
  • 28
  • 38