Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get HTML element width dynamically even on page resize in React?

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;
like image 600
Katyellen Avatar asked Nov 30 '25 20:11

Katyellen


1 Answers

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

import { useEffect, useRef, useState } from "react";

export default function App() {
  const ref = useRef(null);
  const [width, setWidth] = useState(0);

  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);
  }, []);

  return <div ref={ref}>Width: {width}</div>;
}

Edit angry-fast-upe615

like image 185
yousoumar Avatar answered Dec 02 '25 08:12

yousoumar