reactjsuse-ref

React ref.current.clientHeight reports two different values from the same object


I have a requirement for React's ref clientHeight to report the height of a component and I have come across this strange behaviour where the same ref reports different values for its clientHeight depending on how it is accessed. If I output text inside a div the ref outputs the correct height consistently.

  const test = useRef(null)


  useEffect(() => {
        console.log(test)
        console.log(test.current.clientHeight)
    },[])

     return <div ref={test}>
            <Input value={state.multiLineString} multiline/>
        </div>

These images output me accessing clientHeight from the test.current object and directly via test.current.clientHeight. Observe that they reconcile.

enter image description here

These images output me accessing the clientHeight in both the same ways but with the text from state passed to the input which is multiline. Observe that they do not reconcile despite the fact that the first object output has the correct value.

enter image description here

enter image description here

Why is this happening because I am very confused and have exhausted every resource I could find. Thank you.

EDIT

repo here

https://codesandbox.io/s/optimistic-hermann-q6mnv?file=/src/App.js


Solution

  • If you have an area that takes a size later, such as the image area, in the first case, the clientHeight is displayed without calculating that size. In this case, if the container of the image area is given a static height, the correct result will be shown.