Progress bars are great for user engagement because they provide a goal to achieve. Instead of staring at a web page waiting on a resource, you see a progress bar filling up. Progress bars should not be limited to sighted users only. Everyone should be able to understand your progress bar with ease.

So how do you build an accessible progress bar with React?

Create a Progress Bar Component

Create a new component called ProgressBar.js and add the following code:

        const ProgressBar = ({progress}) => {
    return (
        <div>
            <div role="progressbar"
                 aria-valuenow={progress}
                 aria-valuemin={0}
                 aria-valuemax={100}>
                <span>{`${progress}%`}</span>
            </div>
        </div>
    );
};
  
export default ProgressBar;

The first div element is the container and the second div is the actual progress bar. The span element holds the progress bar percentage.

For accessibility purposes, the second div has the following attributes:

  • A role of progressbar.
  • aria-valuenow to indicate the current value of the progress bar.
  • aria-valuemin to indicate the minimum value of the progress bar.
  • aria-valuemax to indicate the maximum value of the progress bar.

The aria-valuemin and aria-valuemax attributes are not necessary if the progress bar maximum and minimum values are 0 and 100 since HTML defaults to these values.

Styling the Progress Bar

You can style the progress bar using inline styles or a CSS-in-JS library like styled-components. Both of these approaches provide a simple way of passing props from the component to the CSS.

You need this functionality because the width of the progress bar depends on the progress value passed in as props.

You can use these inline styles:

        const container = {
    height: 20,
    width: "100%",
    backgroundColor: "#fff",
    borderRadius: 50,
    margin: 50
}
 
const bar = {
    height: "100%",
    width: `${progress}%`,
    backgroundColor: "#90CAF9",
    borderRadius: "inherit",
}
 
const label = {
    padding: "1rem",
    color: "#000000",
}

Modify the return portion of the component to include styles as shown below:

        <div style={container}>
    <div style={bar} role="progressbar"
        aria-valuenow={progress}
        aria-valuemin={0}
        aria-valuemax={100}>
        <span style={label} >{`${progress}%`}</span>
    </div>
</div>

Render the progress bar like this:

        <ProgressBar progress={50}/>

This displays a progress bar with 50 percent complete.

Building Components in React

You can now create an accessible progress bar with percentages that you can reuse in any part of your application. With React, you can create independent UI components like these and use them as building blocks of a complex application.