Using a standard placeholder image for a loading screen in Next.js

I have a requirement to use my background as the loading screen during page transitions in next js. Currently, I have a Loader.js file that contains the following code snippet:

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

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

In addition, in my _app.js file, I am utilizing next/router to handle the routeChangeStart and routeChangeComplete events:

import {useState} 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)
  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} />;
    </>
  );
}

However, I am facing an issue where I do not receive any console logs when trying to switch to another page using the routeChangeStart and routeChangeComplete events.

Answer №1

When working with Next.js, it's common to register events inside a useEffect hook as shown in the examples. I recommend updating your code to follow this pattern:

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} />;
    </>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to determine total revenue by consolidating data from various tables within an IndexedDB database?

Seeking guidance on building a stock/sales application in JavaScript with Dexie.js. I need assistance in efficiently calculating the Total Sales amount without resorting to overly complicated recursive code that triggers multiple queries for a single produ ...

Locating the ASP.NET validator's Control with the help of JQUERY or basic Javascript

On my webpage, I have several textboxes with corresponding ASP.NET validators for validation. I know that I can validate all the validators using a JavaScript function: Page_ClientValidate("myvalidators") where "myvalidators" is the group name of my val ...

Tips for utilizing the "this" keyword in JavaScript

Here's a snippet of code that I'm having trouble with: this.json.each(function(obj, index) { var li = new Element('li'); var a = new Element('a', { 'href': '#', 'rel': obj ...

The varying website layouts across different devices

I recently encountered an issue while working on my WordPress website. When I view the page, some features behave differently than expected. One example is a banner that moves in and out based on scroll position (using jQuery Waypoints). Interestingly, whe ...

Tips for displaying dynamic content based on conditions in React

I am currently working on adjusting the boilerplate repository in order to render different pages based on whether a user is logged in or not. The current setup always displays the same page but includes additional content if there is an authenticated user ...

JavaScript does not acknowledge that one variable is greater than or equal to another

My issue lies in the fact that my code recognizes that 100 is less than 2000, but fails to recognize that 200 is less than 1000. Below is my code snippet (I am also using jQuery as a framework): $('.filter-price').submit(function(e) { var ...

PostMan gives me an error when I attempt to send an image file to NodeJS using multer (req.file is undefined)

After encountering issues with saving image files to the server using multer-s3, I attempted to use multer and s3Client instead. Unfortunately, I faced similar challenges as req.file or req.files from the multer-s3 middleware continued to return undefined. ...

Initiate a project and organize by using mongoose to sort array fields

My mongoose model for a post on a social networking platform is called PostModel: { caption: String, likes: [] // array to store information about users who liked the video, essentially referencing another model comments: [] // array to hold comment object ...

Tips on how to update the styling of an active link

http://jsfiddle.net/G8djC/2/ Looking to create a tabbed area where content changes based on the tab clicked. The Javascript function switches the link class to active upon clicking. However, struggling to change the color of the active tab beyond the firs ...

Having trouble with the search function in my array, as it is consistently returning false instead of the expected result

Aim: I am working on creating a basic search bar that allows users to input a zip code and matches it with zip codes stored in an array. The objective is to develop a function that can determine whether the entered zip code exists in the array or not, and ...

Transform a collection of objects into an array

In my data array, I have various groups and types: const data = [ { groupName: 'groupName1', types: [ { name: 'name1', displayName: 'displayName1' }, { name: 'name2&apos ...

Troubles arise when attempting to bind or watch a service variable that is shared between two

I'm really struggling to understand what's happening here. I grasp the basics of Angular's $digest cycle, and according to this Stack Overflow post, I seem to be correctly assigning a scoped variable to a service's property (an array in ...

What is the process for accomplishing a Node.js redirection with an HTTP POST request?

I have set up app.js to route all requests to my controller.js. Here is an example of what my controller.js code looks like. router.all('/Controller/:id', controller); function controller(req, res){ // Check database using the ID in the URL ...

Exploring the world of mocking and stubbing in protractor

I am interested in testing my angular application using protractor. The app includes an API Module that communicates with the server In these tests, I would like to mock this API Module. I am not looking to perform full integration tests, but rather tests ...

What are the benefits of using Lifery Ajax URLs?

I'm currently using the Grails portlets plugin and I'm exploring how to properly route AJAX methods. It seems like <portlet:actionURL> is only able to map to methods that return models for GSPs, while <portlet:resourceURL> doesn&apos ...

What is the process for retrieving the text from a remotely loaded "<script>" element?

I’m currently in the process of developing an AJAX-enabled Manga reader application for Onemanga using Greasemonkey, specifically JS/jQuery. My issue lies in needing to run one of the inline scripts on their page to update the next page URL. My attempte ...

The use of jQuery.parseJSON is ineffective for a specific string

Why isn't jQuery.parseJSON working on this specific string? ({"stat":"OK","code":400,"data":[{"title":"Development Convention","event_type":false,"dates_and_times":[{"date":"28\/03\/2012","start_time":"10:00 AM","end_time":"10:00 AM"},{"dat ...

Firebase allows for the updating of an object within a nested array

Within Firestore, I have a Document that includes a property named "items" which is of type array. This array consists of ShoppingItem objects with the specified structure: export class ShoppingItem { id?: string; name: string; checked = false; } To ...

Managing shared states across different components in React

After coming across articles that criticize React for its setState functionality, I have realized that some critics may not fully comprehend it. Despite this criticism, I personally appreciate the modularity of React and find it more intuitive as I delve d ...

Exploring the concept of conditional rendering in functional components within NextJs allows for dynamic

Hey there! I've been trying to figure out how to redirect the page if any of the next router query parameters are empty. For example, localhost:3000/page?id=*null/empty* Here's what I have so far: export default function page() { const router ...