NextJs Doesn't include a top loading bar by Default
NextJs doesn't have a top loading bar but instead it has a loading icon with the vercel logo but that doesn't seems nice. Top loading bar looks more attractive and appealing to the users of the website. So in this demo we will see what is the best top loading bar and how to use it.
Different methods of adding a top loading Bar
There are many packages with help with this problems like NProgress, React Top Loading bar and many more. In this demo I will use React Top Loading bar which is simple to use
How to use React Top Loading Bar in NextJS Project
First of all we obviously need to setup a NextJS project. To set up write the command
npx create-next-app top-loading-bar
or yarn create next-app top-loading-bar
.
Then install the package using the command npm i react-top-loading-bar
After that add the package in pages/_app.js in top line
import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/router';
import LoadingBar from 'react-top-loading-bar';
Then set progress state using in the app function
const [progress, setProgress] = useState(0)
After that add it in the return.
<LoadingBar
color='#f59e0b'
progress={progress}
onLoaderFinished={() => setProgress(0)}
/>
Add useEffect so that it runs on pageChange
useEffect(() => {
router.events.on('routeChangeStart', () => {
setProgress(40)
})
router.events.on('routeChangeComplete', () => {
setProgress(100)
})
})
And there you have a successfully created top loading bar.
Comments (0)