Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 462
nrmad Avatar asked Nov 17 '25 04:11

nrmad


2 Answers

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.

like image 137
aliselcuk Avatar answered Nov 18 '25 20:11

aliselcuk


In a case such as yours, you probably should use a callback ref paired with something like ResizeObserver. For ease of use, take a look at the use-resize-observer library.

A code excerpt using this library, taken from their docs:

const App = () => {
  const {
    ref,
    width = 1,
    height = 1,
  } = useResizeObserver();

  return (
    <div ref={ref}>
      Size: {width}x{height}
    </div>
  );
};
like image 22
nascente_diskreta Avatar answered Nov 18 '25 20:11

nascente_diskreta