0

Let's assume I have this hierarchy of components in React 16 application:

component A is composed of components B and C

Those components are represented by block HTML elements with some non-zero height.

in componentDidMount of component B I use vanilla JavaScript in order to find out height of collapsed element. This makes the underlying DOM mutate.

in componentDidMount method of component C I also use vanilla JS to know offset from the top of the components B and C.

I know that the offset of those 2 components can't be the same, but in my initial version of code it was the same. After wrapping offset calculating function in setTimeout I get good measurements.

setTimeout(() => {this.calculateElementsOffset()}, 100)

Is there a way to wire finishing of permutations in component B so I wouldn't use setTimout call in component C with magical 100 ms?

zmii
  • 4,123
  • 3
  • 40
  • 64

1 Answers1

0

Sounds like component C needs to be aware of component B state. Rather than update the DOM with vanilla JS use react to do so. Calculate the needed height for component B in componentDidMount then save that value to state. Use this new state value in a style attribute to give height to the elements that need it and pass this value as a prop into component C. By using setState to store the value you can be sure your components will update.

pizzarob
  • 11,711
  • 6
  • 48
  • 69