Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

626
Views
React, useRef not allowing to access current properties, getting Uncaught TypeError: Cannot read properties of undefined (reading '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:

<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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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 JSX needs 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>
about 4 years ago · Juan Pablo Isaza Report

0

If you are using Next.JS, I think you have to change the dependency to renderedImageRef.current. So something like this:

const [top, setTop]=useState(0)
useEffect(() => {
    if(renderedImageRef.current) {
        setTop(renderedImageRef.current.clientHeight);
    }
}, [renderedImageRef.current])
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!