Home » Get Width and Height of Element in React JS

Get Width and Height of Element in React JS

how to get width of element react js

In this blog post, we will discuss how to get the width and height of an element in React JS. Sometimes in our projects, we may encounter scenarios where we need to dynamically retrieve the height and width of an element in order to perform some layout calculations or to make some changes to the element’s appearance on its size.

In the above demo video, we are getting the width and height values of a card and displaying them inside the card. And we are also updating the width and height values of the card whenever the window is resized.

How to get the width and height of a dynamic element in React JS

In the below example, we are going to use the `offsetWidth` and `offsetHeight` properties to get the width and height of the element.

App.js

import React, { useLayoutEffect, useRef, useState } from "react";

function App() {
  const elementRef = useRef(null);
  const [elementWidth, setElementWidth] = useState(0);
  const [elementHeight, setElementHeight] = useState(0);

  useLayoutEffect(() => {
    function handleResize() {
      if (elementRef.current) {
        const width = elementRef.current.offsetWidth;
        const height = elementRef.current.offsetHeight;
        setElementWidth(width);
        setElementHeight(height);
      }
    }

    handleResize(); // initial call to get width and height of the element
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [elementRef]);

  return (
    <div>
      <div className="card" ref={elementRef}>
        <h3>Get Width and Height</h3>
        <p>
          Width: <strong>{elementWidth}</strong>
        </p>
        <p>
          Height: <strong>{elementHeight}</strong>
        </p>
      </div>
    </div>
  );
}

export default App;

In the above code example, we have created a useRef reference variable `elementRef` to reference the DOM element whose width and height need to be measured.

Then we have defined two state variables `elementWidth` and `elementHeight` to hold the width and height of the element, respectively. The initial value of `elementWidth` and `elementHeight` is set to 0.

The useLayoutEffect hook is used to listen for changes in the size of the element and update the state variables `elementWidth` and `elementHeight` accordingly.

Inside the `useLayoutEffect` hook, an event listener is attached to the window object for the “resize” event. The event listener is set to call the `handleResize()` function whenever the window is resized.

The handleResize function is defined within the useLayoutEffect. Inside the `handleResize` function, we are first checking whether `elementRef.current` exists, which refers to the DOM element that the `elementRef` is referencing.

If it exists, we are getting the offset width and height of the element using the `offsetWidth` and `offsetHeight` properties, respectively. Then, we update the `elementWidth` and `elementHeight` state variables with the obtained width and height values.

Finally, the `useLayoutEffect` hook returns a cleanup function that removes the event listener from the window object when the component is unmounted.

Output

get width and height of dynamic element react js

Also checkout:

We can also use the `clientWidth` and `clientHeight` to get the width and height of an element. Here is an example code.

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

function App() {
  const elementRef = useRef(null);
  const [elementWidth, setElementWidth] = useState(0);
  const [elementHeight, setElementHeight] = useState(0);

  useEffect(() => {
    function handleResize() {
      const width = elementRef.current.clientWidth;
      const height = elementRef.current.clientHeight;
      setElementWidth(width)
      setElementHeight(height)
    }

    handleResize(); // initial call to get width and height of the element
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [elementRef]);

  return (
    <div>
      <div className="card" ref={elementRef}>
        <h3>Get Width and Height</h3>
        <p>
          Width: <strong>{elementWidth}</strong>
        </p>
        <p>
          Height: <strong>{elementHeight}</strong>
        </p>
      </div>
    </div>
  );
}

export default App;

Using `getBoundingClientRect()` to get the width and height of an element.

import React, { useLayoutEffect, useRef, useState } from "react";

function App() {
  const elementRef = useRef(null);
  const [elementWidth, setElementWidth] = useState(0);
  const [elementHeight, setElementHeight] = useState(0);

  useLayoutEffect(() => {
    function handleResize() {
      if (elementRef.current) {
        const rect = elementRef.current.getBoundingClientRect();
        const width = rect.width;
        const height = rect.height;
        setElementWidth(width);
        setElementHeight(height);
      }
    }

    handleResize(); // initial call to get width and height of the element
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, [elementRef]);

  return (
    <div>
      <div className="card" ref={elementRef}>
        <h3>Get Width and Height</h3>
        <p>
          Width: <strong>{elementWidth}</strong>
        </p>
        <p>
          Height: <strong>{elementHeight}</strong>
        </p>
      </div>
    </div>
  );
}

export default App;

Conclusion

In this tutorial, we have discussed different ways to fetch the width and height of an element in React JS and update the component state accordingly. This can be useful in various scenarios where we need to dynamically adjust the layout or make some changes to the element, etc.

Leave a Reply

Your email address will not be published.