How to Find Non Fixed Size HTML Element Dimension in React

Last updated on: by Digamber

Sometimes you have to get the dimension of a dynamically created HTML element to add specific conditions. This guide will cover how to find the width and height of dynamically created HTML elements in React.

Dynamically created HTML elements are those elements which are generated based on the data size. Their dimension, primarily height or width, could be of any size.

Ideally, width and height are set using a fixed number. But in some cases, we might have to set the dimensions dynamically. In this post, we will create a functional component, use React hooks to create a user list and calculate the dimension of HTML elements.

We will use the useState, useRef, useEffect, hooks, and addEventListener methods to get the height and width of list items on window scrolling.

After completing this guide, you will be able to determine the dimensions of elements in React component on the window scroll.

Install New React App

It is required to have Node and NPM installed on your development machine.

You now have to install a new React project; you can execute the given command to form a new project.

npx create-react-app react-demo

Now, you have to enter inside the project directory:

cd react-demo

Build React Component

Let’s build a new component, make the components/User.js file, and this is how a basic functional component looks.

import React from 'react'
function User() {
  return (
    <div></div>
  )
}
export default User

Add Bootstrap Package

Next, Install the Bootstrap library in React application by using the given command.

npm install bootstrap

Calculate Height / Width of Element

Now, you have to insert the following code to the components/User.js file; this will get the react element’s height and width dimensions when user scrolls the page.

import { useState, useRef, useEffect } from "react";
const User = () => {
  const itemRef = useRef();
  const [width, initWidth] = useState();
  const [height, initHeight] = useState();
  const [user, setUser] = useState([
    {
      id: 0,
      data: "Sunt aut facere repellat provident occaecati",
    },
    {
      id: 1,
      data: "Est rerum tempore vitae\nsequi sint nihil",
    },
  ]);
  const addUser = () => {
    const collection = [...user];
    const user = {
      id: collection.length + 1,
      data: `${collection.length + 1}`,
    };
    collection.push(user);
    setUser(collection);
  };
  const getSize = () => {
    const setWidth = itemRef.current.clientWidth;
    initWidth(setWidth);
    const setHeight = itemRef.current.clientHeight;
    initHeight(setHeight);
  };
  useEffect(() => {
    getSize();
  }, [user]);
  useEffect(() => {
    window.addEventListener("resize", getSize);
  }, []);
  return (
    <div>
      <h2 className="mb-2">React Find HTML Element Dimension Example</h2>
      {width && <h4>Width: {width}px</h4>}
      {height && <h4>Height: {height}px</h4>}
      <ul className="list-group mt-5" ref={itemRef}>
        {user.map((data) => (
          <li className="list-group-item" key={data.id}>
            {data.data}
          </li>
        ))}
      </ul>
    </div>
  );
};
export default User;

Add Users Component in React

Now, we are going to add the Users component into the App.js global component. You have to add the given code to the file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import User from "./components/User";
function App() {
  return (
    <div className="container mt-5">
      <User />
    </div>
  );
}
export default App;

Start Development Server

We will start the React development server by executing the following command.

npm start
http://localhost:3000

How to Find Non Fixed Size HTML Element Dimension in React

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.