How to Calculate Height and Width of Dynamic Element in React

Getting the dimension (width/height) of a dynamically created element in React might be difficult, especially when encountering it the first time.

In this tutorial, we will show how to detect the height and width of an HTML element (non-fixed dimension) in React using the useRef Hook.

The useRef Hook permits you to prevail values between renders. Primarily used for: Store a mutable value that does not provoke a re-render when updated—secondly used to access a DOM element directly.

Retrieving the element size dynamically is not a regular task. However, it might be helpful in some instances. Therefore, we will use useRef to get the element width and height.

Download React Project

Before installing a new React app; make sure to have node and npm installed in your system.

Run following command to create new React app.

npx create-react-app my-react-app

Move into the application folder with following command:

cd my-react-app

Create Component File

We are creating a separate component where we can write the logic to calculate element’s dimension.

Hence, move towards src/ folder, within this folder, create features/Post.js folder and file.

import React from 'react'

function Post() {
  return (
    <div>Post</div>
  )
}

export default Post

Install Bootstrap Library

Styling component takes a certain time; we can reduce CSS writing time drastically with Bootstrap. To install the bootstrap package, run the given command.

npm install bootstrap

Get Width and Height of an Element

You must import and use useState, useRef, and useEffect hooks to find the height and width of non-fixed size elements.

Make sure to place the given code to features/Post.js file.

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

const Post = () => {
  const itemRef = useRef();

  const [width, setWidth] = useState();
  const [height, setHeight] = useState();

  const [list, setList] = useState([
    {
      id: 0,
      title: "Sunt aut facere repellat provident occaecati",
    },
    {
      id: 1,
      title: "Est rerum tempore vitae\nsequi sint nihil",
    },
  ]);

  const addPost = () => {
    const items = [...list];
    const post = {
      id: items.length + 1,
      title: `Post title goes here... ${items.length + 1}`,
    };

    items.push(post);
    setList(items);
  };

  const calculateElSize = () => {
    const updatedWidth = itemRef.current.clientWidth;
    setWidth(updatedWidth);

    const updatedHeight = itemRef.current.clientHeight;
    setHeight(updatedHeight);
  };

  useEffect(() => {
    calculateElSize();
  }, [list]);

  useEffect(() => {
    window.addEventListener("resize", calculateElSize);
  }, []);

  return (
    <div>
      <h2 className="mb-3">React Get Element Dimension Example</h2>

      {width && <h4>Width: {width}px</h4>}
      {height && <h4>Height: {height}px</h4>}

      <ul className="list-group mt-5" ref={itemRef}>
        {list.map((data) => (
          <li className="list-group-item" key={data.id}>
            {data.title}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default Post;

Register Home Component

Our component is ready; It needs to be imported in App.js file. This way you can check the output of the Post component on browser.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import Post from "./features/Post";

function App() {
  return (
    <div className="container mt-5">
      <Post />
    </div>
  );
}

export default App;

View App on Browser

To check the project: you must run the given command and start the app using the given URL on the browser.

npm start
http://localhost:3000

How to Calculate Height and Width of Dynamic Element in React

Conclusion

In this post, we have ascertained how to find out the width and height of a component container or dynamically element in React js using React useRef hook.