Skip to content

How to Create a Loading Indicator for Page Transitions in Next.js

Step 1: Create the Preloader Component

Create a new file Preloader.js in the components folder of your project.

components/Preloader.js
const Preloader = () => {
return <div className="preloader">Загрузка...</div>;
};
export default Preloader;

Step 2: Style the Preloader

Add styles for the Preloader component. Create a file preloader.module.css in the same folder as the Preloader component.

components/preloader.module.css
.preloader {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: rgba(0, 0, 0, 0.7);
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 9999;
color: white;
font-size: 1.5rem;
}

Step 3: Use the Preloader

Now you need to include this Preloader in your application so that it appears during page transitions. Edit the _app.js file in the pages folder.

pages/_app.js
import { useRouter } from 'next/router';
import { useEffect, useState } from 'react';
import Preloader from '../components/Preloader';
import styles from '../components/preloader.module.css';
function MyApp({ Component, pageProps }) {
const [loading, setLoading] = useState(false);
const router = useRouter();
useEffect(() => {
const handleStart = () => {
setLoading(true);
};
const handleComplete = () => {
setLoading(false);
};
router.events.on('routeChangeStart', handleStart);
router.events.on('routeChangeComplete', handleComplete);
router.events.on('routeChangeError', handleComplete);
return () => {
router.events.off('routeChangeStart', handleStart);
router.events.off('routeChangeComplete', handleComplete);
router.events.off('routeChangeError', handleComplete);
};
}, []);
return (
<div>
{loading && <Preloader />}
<Component {...pageProps} />
</div>
);
}
export default MyApp;

Conclusion

Now you have a simple preloader that will appear during page transitions in Next.js. Users will see a loading indicator, which improves their experience with your web application.