Build a Custom Progress Bar With Two Divs | by Adriano Triana | Jul, 2022

Create useful components

1*Hwti2mBPtEyy89d4H lBZg
Photo by DS stories:

Progress bars. Simple yet satisfying pieces of UI that make users feel like, well, like they are progressing. So, if you find yourself developing a frontend and come across the need for a progress bar, you have two options: one, import a library that has one premade for you. Two, build it yourself.

This article is going to show you how to do option number two. It’s easier than you may think to build a nice progress bar. I will show you how to do it with just two <div> tags.

TL;DR Scroll to the end for a codesandbox with an example I made if you want to skip the explanation.

This element will define two main things for your progress bar: the neutral color background that will show the part of the progress bar that is not filled in and how tall your progress bar will be.

This div is responsible for the part of the progress bar that will act as the filled-in part of the bar. Because this div lives inside the container div, we give it height 100% so that it fills the height of the progressBarContainer.

The key to getting your progress bar to dynamically show progress is the Width property on the barStyle div. It’s up to you to figure out the logic of how much you want to fill in your progress bar depending on your use case. Once you have that calculation, make sure you feed it as a percent to the barStyle div element, and voila, you have a fully functional progress bar!

Note: Both div elements should have the same border-radius set so that there is no weird overlap between both elements. This creates the effect of the barStyle div being directly overlaid on top of the container div.

Drag the slider to see how the progress bar is affected!

Note that I wrote this codesandbox using the Chakra UI framework. But it is the exact same solution as what I described above. Instead of two divs, I used the Chakra equivalent, which is <Flex>. The styling is the exact same as well though I did get fancy and made the progress bar color a gradient cause I thought it was fun.

The last thing to note is the slider. I added it to make it easier to visualize how your progress bar will fill in as the width of the bar style increases and decreases.

I hope this component is useful and you use it if you ever need a progress bar in the future! You can also make it way fancier, but this is a very simple solution!

News Credit

%d bloggers like this: