Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

177
Vistas
Getting dynamic width of div after rendering

I want to get the width of a dynamic div after it's painted, but I can't tell how. This is what I am doing :

const ref=useRef();
useEffect(()=>{
console.log('REF',ref.current.offSetWidth)
},[])



return (
<div ref={ref}>


</div>

I tried window.resize eventListener, but it only gets triggered if the screen dimensions changed. My question is there anyway to get the width of a div after it renders on the screen ? I'm not setting the width beforehand, it's just taking 100% of parent element inside a flex box

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can use the ResizeObserver, a simple implementation with React could be something like this:

import {useRef, useEffect} from 'react'

export default function App() {
  const divRef = useRef()

  useEffect(() => {
    new ResizeObserver(() => {
      console.log('Width: ', divRef.current.clientWidth)
    }).observe(divRef.current)
  }, [])

  return (
    <div ref={divRef}>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Your code is working I think. Here is a short Typescript implementation to show my point:

...

const ref = useRef<HTMLDivElement>();
    return (
        <div ref={ref as MutableRefObject<HTMLDivElement>}>
            <button onClick={() => console.log('REF', ref?.current?.clientWidth)}>TEST</button>
        </div>
    );

...

Console result on button click before resizing: [![enter image description here][1]][1]

Console result on button click after resizing: [![enter image description here][2]][2]

I guess the reason you never see the changes is that you have a use effect here that only runs once. Also note that changes in the ref object will not automatically trigger a re-render. [1]: https://i.stack.imgur.com/uCmz4.png [2]: https://i.stack.imgur.com/cWpVM.png

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda