How to create a Loader between Route Navigation on Next 13

84 views Asked by At

I would like to put a Loading in my Screen between Route Navigation on Next 13 to indicate to the user that we have a navigation in progress

I tried using the old method, but I am struggling with I can not use next/router in a Client Component

1

There are 1 answers

4
Par Tha On

1.Create a new file called Loader.js in your components directory.

2.In Loader.js, add the following code:

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.In your main layout component (e.g., Layout.js), import and use the Loader component:

import Loader from './Loader';

const Layout = ({ children }) => {
  return (
    <div>
      <Loader />
      {children}
    </div>
  );
};

export default Layout;

4.Wrap your pages or components that require the loading indicator with the Layout component:

import Layout from '../components/Layout';

const HomePage = () => {
  return (
    <Layout>
      {/* Your page content */}
    </Layout>
  );
};

export default HomePage;