React: How to get the ref height of an element coming from the children with dynamic height?

430 views Asked by At

I have a component that has some element with text.
Based on some other stuff the text can be some words or can be a wall of text. From the parent I need to know the exact height at any time of the element inside of the children
I have tried using callback refs but to no avails. I can only get the first value but then I need it to update

https://codesandbox.io/s/nervous-mendeleev-xf2cg?file=/src/App.js

Here is an example of the code.


Update: one thing that I notice when I check directly the height is that I get the previous value (kinda like when you use setState and dont realize it is asynchronous)

when small ( height: ~60) it shows ~100
when big the other way around

1

There are 1 answers

2
95faf8e76605e973 On BEST ANSWER

one thing that I notice when I check directly the height is that I get the previous value

You can still salvage this solution. It is getting the previous value because you are checking for the height right away but the issue is that the component is not done rendering using the new words (i.e., the ref height would still return the previous height).

What you can do is to leverage useEffect. When the component is done rendering (equivalent of this in class implementation is componentDidUpdate), that is when you start checking its height.

useEffect(() => {
  // the component is done rendering - now you can check for its new height here
}, [words, onClick]);

Edit determined-panini-4oxmz