Prerequisites
- Next.js application with version 11 or higher
Getting started
Firstly, we must install the NProgress
npm module
npm install nprogress
bash
And its types
npm install --save-dev @types/nprogress
bash
Usage
Importing styles
Custom app
If you do not have an _app file yet, you can copy this template below. This example comes from Next.js' docs.
Open template
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
tsx
To use the module, open your _app.tsx
file. We must import the required styles from
nprogress.
import "nprogress/nprogress.css";
export default function MyApp({ Component, pageProps, router }) {
return; /* ... */
}
tsx
Router events
We'll add a useEffect
in our component and add 2 handlers to handle routeChangeStart
and routeChangeComplete
.
More info about router events.
import * as React from "react";
import NProgress from "nprogress";
export default function MyApp({ Component, pageProps, router }) {
/* ... */
React.useEffect(() => {
const handleRouteStart = () => NProgress.start();
const handleRouteDone = () => NProgress.done();
router.events.on("routeChangeStart", handleRouteStart);
router.events.on("routeChangeComplete", handleRouteDone);
router.events.on("routeChangeError", handleRouteDone);
return () => {
// Make sure to remove the event handler on unmount!
router.events.off("routeChangeStart", handleRouteStart);
router.events.off("routeChangeComplete", handleRouteDone);
router.events.off("routeChangeError", handleRouteDone);
};
}, []);
/* ... */
}
tsx
Done
That's it! Start your dev server and see the changes!