Adding a top page loader between route transitions in Next.js

date
Nov 19, 2021
slug
nextjs-route-transiton-top-loader
status
Published
tags
Next.js
summary
type
Post
We will be using nProgress package to add the route transition loader. Install it using:
npm i nProgress
or
yarn add nProgress
 
Now create a nProgress.js component
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import NProgress from 'nprogress'

export default function Progress() {
  const router = useRouter()

  useEffect(() => {
    const start = () => NProgress.start()
    const done = () => 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)
    }
  }, [router.events])

  return <></>
}
Here we are using the next.js routers' different hooks like routeChangeStart, routeChangeComplete, and routeChangeError to trigger the start and end animations of the nProgress package.
To style our loader, create a nProgress.css file in your styles folder.
#nprogress {
  pointer-events: none;
}

#nprogress .bar {
  background-color: MediumVioletRed;
  position: fixed;
  z-index: 1031;
  top: 0;
  left: 0;
  width: 100%;
  height: 2px;
}
 
Now finish the setup by adding the component and it's styles in the _app.js file.
import NProgress from '../components/nProgress'

import '../styles/nProgress.css'

function MyApp({ Component, pageProps }) {
  return (
    <>
      <Component {...pageProps} />
      <NProgress />
    </>
  )
}

export default MyApp 
 

© Nikit Singh 2020 - 2024