6

I'm calling a function in React within componentDidMount that queries the DOM however the DOM isn't rendered in time even though i'm calling it after componentDidMount.

The strange thing is that in webpack it all works fine and the DOM is rendered and ready for my querySelectorAll. However when built it isn't. I've tried on multiple server types and its always the same.

My initial thoughts are that minifying the code is messing it up somehow.

I only require the function to run once so that's why i placed it in component did mount

Turan
  • 302
  • 2
  • 9
  • 1
    Have some code to show us? Maybe we can help debug it if you let us :) – Kyle Richardson Apr 17 '18 at 21:04
  • 1
    I'm not sure what I can add to this, but I'm currently dealing with a same behavior - I have an animated scrolling on componentDidMount, which is failing to properly retrieve elements offsetTop. If I wrap it in setTimeout for even 1ms - offsetTop is calculated correctly, so, practically, I'd say react is not done with DOM in componentDidMount – Stormherz Apr 18 '18 at 14:14

2 Answers2

2

As explained in this answer, componentDidMount is called after all the children components have been mounted, but before any parent components have been mounted.

For me it worked to delay my code using setTimeout() (with 0 ms delay) from within componentDidMount.

cdauth
  • 6,171
  • 3
  • 41
  • 49
1

componentDidMount is only called once in the lifecycle of any component, render againt will not reinitialize the component. Have you ever try with componentDidUpdate. This hit when component is updated.

Simon Restrepo
  • 313
  • 1
  • 2
  • 15