How to Create an Accessible Progress Bar With React

Progress bars are great for user interaction as they indicate a goal to reach. Instead of staring at a web page waiting for a resource, you see a progress bar filling up. Progress bars shouldn’t just be limited to sighted users. Everyone should be able to understand your progress bar with ease.


So how do you create 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 contains the percentage of the progress bar.

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

  • A scroll of the progress bar.
  • aria-valuenow to show the current value of the progress bar.
  • aria-valuemin to specify the minimum value of the progress bar.
  • aria-valuemax to specify the maximum value of the progress bar.

The aria-valuemin and aria-valuemax attributes are not required if the maximum and minimum values ​​of the progress bar are 0 and 100, respectively, since HTML uses these values ​​by default.

Styling the progress bar

You can style the progress bar with inline styles or a CSS-in-JS library like styled-components. Both approaches provide an easy way to pass props from the component to the CSS.

You need this functionality because the width of the progress bar depends on the progress value passed 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 part 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 as follows:

<ProgressBar progress={50}/>

This displays a progress bar with 50 percent complete.

components in response

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

Leave a Reply

Your email address will not be published. Required fields are marked *