In the image above, the blue line is a progress bar that tells us if a web app has loaded or not. This progress bar is not super important for a web app, but it does help retain a user’s attention while the page loads. In this shot, we will learn how to create a progress bar in a web app.
We will use the NProgress
package. In this shot, we will use Next.js to implement the package, but you should also be able to implement it in other technologies, such as plain React.
Install the NProgress
package with this command:
npm install nprogress
In any main file, such as _app.js
, import the resources as shown in the code snippet below. Then, inside your component, paste the first three lines 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();
// ...
}
Now it’s time to style the progress bar. Add a file called nprogress.css
in your codebase and link your app to it. Since I’m using Next.js, I use the link
tag to connect that CSS file.
<link rel="stylesheet" type="text/css" href="/nprogress.css" />
If you copy and paste the code snippet below, you’ll be able to see the exact bar from the beginning of the shot. Feel free to play around with it and change details like the color, the width of the 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);
}