Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useRef not allowing to access .current.clientHeight

I’m storing a reference to an image item using: const renderedImageRef = useRef().

The ref is then assigned in render() function using:

<img ref={renderedImageRef} src=... />

In another JSX item below, I try to access renderedImageRef.current.clientHeight using:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div style={{top: `${renderedImageRef.current.clientHeight}px`}}>Hello world</div>

but this produces an error in the console:

Uncaught TypeError: Cannot read properties of undefined (reading 'clientHeight')

Strangely enough, if I try to access renderedImageRef.current.clientHeight from inside a useEffect hook, it displays the height correctly:

useEffect(() => {
    if(renderedImageRef !== null) {
        console.log(renderedImageRef)
    }
}, [renderedImageRef])

Why am I getting the console error?

>Solution :

A possible answer is that this line :

<div style={{top: `${renderedImageRef.current.clientHeight}px`}}>Hello world</div>

is coming in your code before this one:

<img ref={renderedImageRef} src=... />

In witch case it is normal that you are getting the error. It is to know that when you call const renderedImageRef = useRef(), the value of renderedImageRef is {current:undefined} The html need to be rendered before a ref gets its value in current field.

A solution is to use a state for the top :

const [top, setTop]=useState(0)
useEffect(() => {
    if(renderedImageRef.current) {
        setTop(renderedImageRef.current.clientHeight);
    }
}, [renderedImageRef])
<div style={{top:`${top}px`}}>Hello world</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading