How to create progress bar in react js?
March 28, 2023Hi Friends π,
Welcome To aGuideHub!
To create progress bar in React js, you have to use any progress bar
package library or you have to write a custom progress bar
component. It will create progress bar in react js.
Today, I am going to show you, how to create progress bar in react js.
Table of contents
- Set up the React project.
- Import necessary components.
- Create the progress bar component.
Letβs start with the first step.
Step 1: Set up the React project.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import necessary components.
Create a new file called "./progress-bar.component"
in the src/components directory. This file will contain the ProgressBar component.
import React, { useState, useEffect } from "react";
import ProgressBar from "./progress-bar.component";
Step 3: Create the progress bar component.
In this example, which shows progress bar
with percentage width based on prop
value same is passed as a prop to progressbar
component.
<div className="App">
<ProgressBar bgcolor={"#6a1b9a"} completed={completed} />
</div>
ReactJS create the progress bar example.
The below code is an example of,The useState hook is used to create an absolute state variable that starts
with a value
of 0
.
App.js
import React, { useState, useEffect } from "react";
import ProgressBar from "./progress-bar.component";
function App() {
const [completed, setCompleted] = useState(0);
useEffect(() => {
setInterval(() => setCompleted(Math.floor(Math.random() * 100) + 1), 2000);
}, []);
return (
<div className="App">
<ProgressBar bgcolor={"#6a1b9a"} completed={completed} />
</div>
);
}
export default App;
// progress-bar.component.js
import React from "react";
const ProgressBar = (props) => {
const { bgcolor, completed } = props;
const containerStyles = {
height: 20,
width: '100%',
backgroundColor: "#e0e0de",
borderRadius: 50,
margin: 50,
}
const fillerStyles = {
height: '100%',
width: `${completed}%`,
backgroundColor: bgcolor,
transition: 'width 1s ease-in-out',
borderRadius: 'inherit',
textAlign: 'right',
}
const labelStyles = {
padding: 5,
color: 'white',
fontWeight: 'bold',
}
return (
<div style={containerStyles}>
<div style={fillerStyles}>
<span style={labelStyles}>{`${completed}%`}</span>
</div>
</div>
);
};
export default ProgressBar;
Check the output of the above code example.
Here, we are provided code sandbox links for the above program create progress bar in React js. Then you can use whenever you went and do the changes as per your requirements.
All the best π