Adding a Page Progress Bar with nprogress - Modern Next.js Blog Series #23
- Published on
This article is also published at it 邦幫忙 2022 iThome Ironman Contest
This is the 23rd article in the "Modern Blog 30 Days" series.
After optimizing image performance in the previous article, we continue to improve perceived performance for readers by adding a page transition progress bar using nprogress!
The final effect is as follows:
The code changes for this article are as follows:
Adding a Page Progress Bar with nprogress
Installing nprogress in Next.js
Copied!pnpm add nprogress pnpm add -D @types/nprogress
Modify src/pages/_app.tsx
:
Copied!// ... // Import nprogress/nprogress.css import "nprogress/nprogress.css"; // ... // Import NProgress, useRouter, useEffect import { useRouter } from "next/router"; import NProgress from "nprogress"; import { useEffect } from "react"; // Call NProgress.configure to initialize NProgress.configure({ showSpinner: false }); function MyApp({ Component, pageProps }: AppProps) { // Add the following useEffect block to start NProgress during Next.js page transitions and stop it when the transition is complete const router = useRouter(); // Integrate nprogress useEffect(() => { router.events.on("routeChangeStart", () => NProgress.start()); router.events.on("routeChangeComplete", () => NProgress.done()); router.events.on("routeChangeError", () => NProgress.done()); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // ... }
Adjusting the Progress Bar Color
The progress bar is blue by default. To change it, you can write CSS to change the color.
Add src/styles/nprogress-custom.scss
:
Copied!#nprogress { .bar { @apply h-1 bg-primary-500; } .peg { @apply shadow-[0_0_10px] shadow-primary-500; } }
Modify src/pages/_app.tsx
to globally import the new scss file:
Copied!import "@/styles/globals.css"; import "@/styles/prism-dracula.css"; import "@/styles/prism-plus.css"; import "nprogress/nprogress.css"; // Add the following line to import nprogress-custom.scss import "@/styles/nprogress-custom.scss"; // ...
Results
Done! Use pnpm dev
, and after entering the website and clicking links to switch pages, you will see a progress bar at the top during page transitions! It makes visitors more willing to wait for the page to load.
The final effect is as follows:
The code changes for this article are as follows:
References
- rstacruz/nprogress: For slim progress bars like on YouTube, Medium, etc
- The comprehensive guide to use NProgress in Next.js [easy guide]
Next Article
Congratulations on successfully adding a page progress bar with nprogress!
In the next article, we will continue to add more dazzling features. Let's add a "Table of Contents" to article pages, providing readers with a clear overview of the article structure.