Yang
It's really simple to set up especially Next.js projects to use nprogress, and using it greatly improves the UX for users on slow connections that are trying to interact with your site. It shows a neat progress bar at the top of the window that keeps incrementing up until 100% in a realistic way to give the user the illusion that something is being loaded behind the scenes.
Add and to your project.
<script src='nprogress.js'></script>
<link rel='stylesheet' href='nprogress.css'/>
NProgress is available via bower and npm.
$ npm install --save nprogress
// components/nprogress.tsx
import NProgress from 'nprogress';
import { useRouter } from 'next/router';
import { useEffect } from 'react';
export default function Progress() {
const router = useRouter();
useEffect(() => {
let timeout: NodeJS.Timeout;
const start = () => {
timeout = setTimeout(NProgress.start, 100);
};
const done = () => {
clearTimeout(timeout);
NProgress.done();
};
router.events.on('routeChangeStart', start);
router.events.on('routeChangeComplete', done);
router.events.on('routeChangeError', done);
return () => {
router.events.off('routeChangeStart', start);
router.events.off('routeChangeComplete', done);
router.events.off('routeChangeError', done);
};
}, []);
return <></>;
}
/* nprogress.css */
/* Make clicks pass-through */
#nprogress {
pointer-events: none;
}
#nprogress .bar {
background: #845ef7;
position: fixed;
z-index: 1031;
top: 0;
left: 0;
width: 100%;
height: 2px;
}
// pages/_app.tsx
import '@styles/nprogress.css';
import type { AppProps } from 'next/app';
import NProgress from '../components/nprogress';
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<Component {...pageProps} />
<NProgress />
</>
);
}
I’m a curiosity-driven, full-stack web developer