Creating a Progress Bar Part 2

In our previous blog post, we showed you how to create a basic progress bar using HTML and CSS. In this tutorial, we’ll update that code to use React and create a reusable progress bar component.

Creating the Progress Bar Component

Now that we have our project set up, let’s create a new component for our progress bar. In your code editor, create a new file called ProgressBar.js in the src directory and add the following code:

import React from 'react';

const ProgressBar = ({ progress }) => {
  return (
    <div className="progress-bar">
      <div className="progress" style={{ width: `${progress}%` }}></div>
    </div>
  );
};

export default ProgressBar;

In this code, we’ve defined a new component called ProgressBar. It takes a single prop called progress, which is a number between 0 and 100 that represents the progress percentage.

Inside the component, we’re using the same HTML structure as before to create the progress bar. However, we’ve added an inline style to the progress element to set its width based on the progress prop. This will allow us to update the progress dynamically based on the value of progress.

Finally, we’re exporting the ProgressBar component so that we can use it in other parts of our application.

Using the Progress Bar Component

Now that we have our ProgressBar component defined, let’s use it in our App.js file to test it out. Replace the contents of App.js with the following code:

import React, { useState } from 'react';
import ProgressBar from './ProgressBar';

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

  const handleIncreaseClick = () => {
    setProgress(progress + 10);
  };

  const handleDecreaseClick = () => {
    setProgress(progress - 10);
  };

  return (
    <div className="App">
      <ProgressBar progress={progress} />
      <div>
        <button onClick={handleDecreaseClick}>Decrease Progress</button>
        <button onClick={handleIncreaseClick}>Increase Progress</button>
      </div>
    </div>
  );
}

export default App;

In this code, we’ve imported the ProgressBar component and added it to our App component. We’re passing in a progress prop of 50 to start with.

We’ve also added two buttons to increase and decrease the progress. We’re using the useState hook to keep track of the progress and update it when the buttons are clicked.

Now if you run your React app (npm start), you should see a progress bar displayed on the screen with two buttons to increase and decrease the progress.

Conclusion

By using React to create a reusable progress bar component, we can easily update the progress dynamically and use the component throughout our application. Of course, you can customize the design and layout of the progress bar to match your website’s style.

Facebook Comments