This is a recurring problem I have with React. The componentDidMount
method is guaranteed to be fired when the component is rendered for the first time so it seems like a natural place to take DOM measurements like heights and offsets.
However, many times I receive wrong style readings at this point of the component's lifecycle. The component is in the DOM, when I break with the debugger, but it's not yet painted on the screen. I get this problem with elements that have width/height set to 100% mostly.
When I take measurements in componentDidUpdate
- everything works fine, but this method will not fire at the initial render of the component.
So my question is - when exactly is componentDidMount
fired because it's obviously not fired after all the browser paints are done.
EDIT: This Stackoverflow issue deals with the same subject:
It also references this github conversation that explains what happens
Inside a react component tree, componentDidMount()
is fired after all children components have also been mounted. This means, that any component's componentDidMount()
is fired before its parent has been mounted.
So if you want to measure DOM position and sizes etc, using componentDidMount()
of a child component is an unsafe place/ time to do this.
In your case: to get accurate reading from 100% width/height components, a safe place to take such measurements would be inside the componentDidMount()
of the top react component.
100% is a width/height relative to the parent/ container. So measurements can only be taken after the parent has been mounted too.