Clue Mediator

How to add a Progress Bar in React

📅July 27, 2021

Today we will show you how to add a Progress Bar in React application.

Here, we will create a small application to show the progress bar using bootstrap. To indicate the progress count, we will use the `setInterval` function.

Checkout more articles on ReactJS

Demo Application

Output - How to add a Progress Bar in React - Clue Mediator

Output - How to add a Progress Bar in React - Clue Mediator

Steps to add a progress bar in react

  1. Create a react app and add bootstrap
  2. Write component to add progress bar
  3. Output

1. Create a react app and add bootstrap

Let’s create a react application using the create-react-app npm package and install the bootstrap package in the react app.

Check the following article, if you don’t know how to add bootstrap in react.

How to add Bootstrap in React

2. Write component to add progress bar

First of all, we will set the interval on load to increase the progress count.

const [progress, setProgress] = useState(0);

useEffect(() => {
  progressInterval = setInterval(() => {
    setProgress(prev => prev + 1);
  }, 100);
}, []);

Let's write a logic to stop it when the counter reaches `100`.

useEffect(() => {
  if (progress >= 100) {
    clearInterval(progressInterval);
  }
}, [progress]);

Finally, Draw a progress bar based on the counter.

<div 30="" class="progress w-50" style={{ height: }}>
  <div class="progress-bar" role="progressbar" style={{ width: `${progress}%` }}>{progress}%</div>
</div>

3. Output

Combine all of the above code together and see how it looks.

App.js

import React, { useEffect, useState } from 'react';

let progressInterval = null;

function App() {
  const [progress, setProgress] = useState(0);

  useEffect(() => {
    progressInterval = setInterval(() => {
      setProgress(prev => prev + 1);
    }, 100);
  }, []);

  useEffect(() => {
    if (progress >= 100) {
      clearInterval(progressInterval);
    }
  }, [progress]);

  return (
    <div class="m-5">
      <h5 class="mb-3">Progress Bar in React - <a href="https://cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h5>
      <div 30="" class="progress w-50" style={{ height: }}>
        <div class="progress-bar" role="progressbar" style={{ width: `${progress}%` }}>{progress}%</div>
      </div>
    </div>
  );
}

export default App;

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository StackBlitz Project