DEV Community

Mohmed Ishak
Mohmed Ishak

Posted on

How To Easily Create Cool Progress Bar in Your Web App?

Mohmed Ishak
Hello, devs! Do you see the picture above? That blue line is a progress bar. It tells you how much if a web app has loaded or not. It is not super important for a web app, but it really helps you to retain user's attention while the page loads for a second or two. So, how do you create that?

Of course, we're gonna use a package because someone else worked hard already to implement this, so why not use it? The package is called NProgress. In this article, I'll teach you how to implement it using Next.js, but if I'm sure you'll be able to implement it in other technologies such as plain React and so on.

Step 1

Install NProgress package with this command:

npm install nprogress
Enter fullscreen mode Exit fullscreen mode

Step 2

In any main file such as _app.js (Next.js devs would know), just import these stuffs I've imported (refer code snippet below). Then, inside your component, paste the first three lines which I wrote under function JustAComponent() { ...

import nprogress from "nprogress";
import Router, { useRouter } from "next/router";

function JustAComponent() {
  Router.onRouteChangeStart = () => nprogress.start();
  Router.onRouteChangeComplete = () => nprogress.done();
  Router.onRouteChangeError = () => nprogress.done();

// ...
}
Enter fullscreen mode Exit fullscreen mode

Step 3

Now it's time to style your progress bar. Add a file called nprogress.css in your codebase and link your app to it. In my case, since I'm using Next.js, I connected that CSS file using the link tag.

<link rel="stylesheet" type="text/css" href="/nprogress.css" />
Enter fullscreen mode Exit fullscreen mode

Step 4

If you copy and paste the code snippet below, you'll be able to see the exact bar which I shared at the very top of this article, but feel free to play around with it and change stuffs like color, width of progress bar, etc.

#nprogress {
  pointer-events: none;
}

#nprogress .bar {
  background: var(--progressBar);
  position: fixed;
  z-index: 1031;
  top: 0;
  left: 0;
  background-color: #3943b7;
  width: 100%;
  height: 5px;
}

#nprogress .peg {
  display: block;
  position: absolute;
  right: 0px;
  width: 100px;
  height: 100%;
  box-shadow: 0 0 10px var(--progressBar), 0 0 5px var(--progressBar);
  opacity: 1;
  -webkit-transform: rotate(3deg) translate(0px, -4px);
  -ms-transform: rotate(3deg) translate(0px, -4px);
  transform: rotate(3deg) translate(0px, -4px);
}
Enter fullscreen mode Exit fullscreen mode

Done. If you like this article, all I need is just a like. :)

Top comments (0)