Click here to Skip to main content
15,889,838 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to have my background as the loading screen between the page transitions in next js.

But I'm not able to get any console logs from my routeChangeStart and routeChangeComplete events when I try to switch to another page.

What I have tried:

Currently I have a Loader.js file that stores my image:-

import styles from './layout.module.css'

export default function Loader(){
    return(
        <div className={styles.loaderContainer}>
            <img src="../uploads/bg1080x1920.jpg" />
            <div>Loading ...</div> 
        </div>
    )


And in my _app.js I am using next/router for handling the routeChangeStart and routeChangeComplete events:

import {useState, useEffect} from "react";
import { useRouter } from "next/router";
import Loader from "../components/Loader"

export default function App({ Component, pageProps }) {
  const router = useRouter()
  const [loading, setLoading] = useState(false)

  useEffect(() => { //<-- this useEffect will be triggered just one time at component initialization
      router.events.on("routeChangeStart", (url) => {
         console.log("Route is changing");
         setLoading(true)
      });
      router.events.on("routeChangeComplete", (url) => {
         console.log("Route is changed");
         setLoading(false)
      });
  }, []);
  
  return (
    <>
    {loading && <Loader />}
    <Component {...pageProps} />;
    </>
  );
}
Posted
Updated 28-Jul-21 1:30am
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900