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

617
Views
Reaccionar, useRef no permite acceder a las propiedades actuales, obteniendo TypeError no capturado: no se pueden leer las propiedades de undefined (leyendo 'clientHeight')

Estoy almacenando una referencia a un elemento de imagen usando: const renderedImageRef = useRef() . Luego, la referencia se asigna en la función render() usando:

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

En otro elemento JSX a continuación, intento acceder a renderedImageRef.current.clientHeight usando:

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

Pero esto produce un error en la consola:

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

Por extraño que parezca, si trato de acceder a useEffect renderedImageRef.current.clientHeight muestra la altura correctamente:

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

¿Por qué recibo el error de la consola?

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

0

Una posible respuesta es que esta línea:

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

viene en su código antes de este:

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

En caso de brujas, es normal que esté recibiendo el error. Es importante saber que cuando llamas a const renderedImageRef = useRef() , el valor de renderedImageRef es {current:undefined} . El JSX debe representarse antes de que una ref obtenga su valor en el campo current .

Una solución es usar un estado para la 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

Si está utilizando Next.JS, creo que debe cambiar la dependencia a renderingImageRef.current. Así que algo como esto:

 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!