DEV Community

Dharmesh
Dharmesh

Posted on

Building Dynamic Multiple Progress Bars in React + TypeScript

Building Dynamic Multiple Progress Bars in React + TypeScript

In this example, we dynamically create multiple progress bars and update each one independently using setInterval.

Features

  • Add unlimited progress bars
  • Independent progress animation
  • React Hooks
  • TypeScript support
  • Clean and reusable logic

Full Code

import { useEffect, useState } from "react";

type ProgressBarType = {
  id: number;
  progress: number;
};

export default function Progressbar() {
  const [progressbarList, setProgressbarList] = useState<
    ProgressBarType[]
  >([]);

  useEffect(() => {
    const timers = progressbarList.map((bar) => {
      return setInterval(() => {
        setProgressbarList((prev) =>
          prev.map((item) => {
            if (item.id === bar.id) {
              if (item.progress >= 100) {
                return item;
              }

              return {
                ...item,
                progress: item.progress + 1,
              };
            }

            return item;
          })
        );
      }, 100);
    });

    return () => {
      timers.forEach((timer) => clearInterval(timer));
    };
  }, [progressbarList.length]);

  const handleAddProgressbar = () => {
    setProgressbarList((prev) => [
      ...prev,
      {
        id: Date.now(),
        progress: 0,
      },
    ]);
  };

  return (
    <div className="space-y-5 p-5">
      <button
        className="px-4 py-2 bg-blue-500 text-white rounded-lg"
        onClick={handleAddProgressbar}
      >
        Add Progress Bar
      </button>

      {progressbarList.map((progressbar) => (
        <div
          key={progressbar.id}
          className="relative h-6 overflow-hidden border rounded-2xl"
        >
          <div
            style={{
              width: `${progressbar.progress}%`,
            }}
            className="absolute left-0 top-0 flex h-full items-center justify-center bg-amber-400 transition-all duration-300"
          >
            {progressbar.progress}%
          </div>
        </div>
      ))}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Concepts Used

useState

Used for storing all progress bars.

useEffect

Used to create intervals for each progress bar.

setInterval

Updates progress continuously.

Immutable State Update

Using .map() to update only the targeted progress bar.


Key Learning

A very common React interview question is:

"How would you build multiple independent progress bars dynamically?"

This is a clean solution using React Hooks and TypeScript.


Possible Improvements

  • Pause/Resume functionality
  • Remove progress bar
  • Cancel upload simulation
  • Real file upload integration
  • Framer Motion animation
  • Custom speed per progress bar

Thanks for reading!

Top comments (0)