1. Begin by creating a new file named Loader.js within your components folder.
2. Inside Loader.js, insert the code snippet below:
import { useEffect, useState } from 'react';
const Loader = () => {
const [loading, setLoading] = useState(false);
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 loading ? <div>Loading...</div> : null;
};
export default Loader;
3. Within your main layout component (for example, Layout.js), import and utilize the Loader component:
import Loader from './Loader';
const Layout = ({ children }) => {
return (
<div>
<Loader />
{children}
</div>
);
};
export default Layout;
4. Surround your pages or components that need the loading indicator with the Layout component:
import Layout from '../components/Layout';
const HomePage = () => {
return (
<Layout>
{/* Your page content */}
</Layout>
);
};
export default HomePage;