How to add a Progress Bar in React
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
Steps to add a progress bar in react
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.
2. Write component to add progress bar
First of all, we will set the interval on load to increase the progress count.
1 2 3 4 5 6 7 | 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
.
1 2 3 4 5 | useEffect(() => { if (progress >= 100) { clearInterval(progressInterval); } }, [progress]); |
Finally, Draw a progress bar based on the counter.
1 2 3 | <div classname="progress w-50" style="{{" height:="" 30="" }}=""> <div classname="progress-bar" role="progressbar" style="{{" width:="" `${progress}%`="" }}="">{progress}%</div> </div> |
3. Output
Combine all of the above code together and see how it looks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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 classname="m-5"> <h5 classname="mb-3">Progress Bar in React - <a href="https://cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h5> <div classname="progress w-50" style="{{" height:="" 30="" }}=""> <div classname="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..!! 🙂