Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

176
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda