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

700
Visualizações
How to get HTML element width dynamically in React.js?

I would like to dynamically get the div element's width. With useRef I can get the width of my div, but when I resize my page, the width value doesn't update automatically. Can you tell me what I need to do to make this happen?

Here's my code I put into Codesandbox.io, and an overview here:

import React from "react";
import "./styles.css";

const App = () => {
  const ref = React.useRef(null);
  const [width, setWidth] = React.useState(0);

  React.useEffect(() => {
    setWidth(ref.current.offsetWidth);
  }, [width]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <div
        style={{
          border: "1px solid red"
        }}
        ref={ref}
      >
        Width: {width}
      </div>
    </div>
  );
};

export default App;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Change your useEffect as below so you add an event listener for when you resize the page. Updated Codesandbox here. Also notice I removed width state from the dependency array.

React.useEffect(() => {
    // when the component gets mounted
    setWidth(ref.current.offsetWidth); 
    // to handle page resize
    const getwidth = ()=>{
      setWidth(ref.current.offsetWidth);
    }
    window.addEventListener("resize", getwidth);
    // remove the event listener before the component gets unmounted
    return ()=>window.removeEventListener("resize", getwidth)
  }, []);
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