NextJs only displays loading animation once

Currently, I am developing an app using Next.js and I am facing a challenge with implementing a loading animation. The animation I am attempting to incorporate consists of three bouncing balls which display correctly. When I launch the Next.js app with npm run dev, the animation works as expected and reloads properly when I refresh the page. However, if I navigate to a different route, the animation fails to appear. The elements seem to be missing altogether. I am unsure of the reason behind this issue and have included the code below for context.

import React from "react";
import Image from 'next/image'

import styled from "styled-components";

const Screen = styled.div`
  position: relative;
  height: 100vh;
  width: 100%;
  opacity: 0;
  animation: fade 0.4s ease-in forwards;

  @keyframes fade {
    0% {
      opacity: 0.4;
    }
    50% {
      opacity: 0.8;
    }
    100% {
      opacity: 1;
    }
  }
`;

const Balls = styled.div`
  display: flex;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);

  .ball {
    height: 30px;
    width: 30px;
    border-radius: 50%;
    background: #E60E33;
    margin: 0 60px 0 0;
    animation: oscillate 0.7s ease-in forwards infinite;
  }

  .one {
    animation-delay: 0.5s;
  }
  .two {
    animation-delay: 1s;
  }
  .three {
    animation-delay: 1.5s;
  }

  @keyframes oscillate {
    0% {
      transform: translateY(0);
    }
    50% {
      transform: translateY(20px);
    }
    100% {
      transform: translateY(0);
    }
  }
`;


function MyApp({ Component, pageProps }) {
  const [loading, setLoading] = React.useState(false);

  React.useEffect(() =>{
    setTimeout(() => setLoading(true), 5000);
   })

  return (
    <>
      {loading ? (
        <React.Fragment>
          <Component {...pageProps} />
        </React.Fragment>
      ) : (
        <Screen>
        <div
        style={{
          display: "flex",
          position: "absolute",
          top: "35%",
          left: "48%",
          transform: "translate(-50%, -50%)"
        }}
      >
          </div>
          <Balls>
             <div className="ball one"></div>
            <div className="ball two"></div>
            <div className="ball three"></div>
          </Balls>
        </Screen>
       )}
    </>
  );
}

export default MyApp

Answer №1

Don't forget to reset the loading state before proceeding

  const router = useRouter()

  React.useEffect(() => {
    setLoading(false);
    setTimeout(() => setLoading(true), 5000);
   }, [router.asPath])

Remember to include the route path as a dependency to prevent endless loops.

Consider switching the values of true and false for clarity. It's a bit confusing when the app is loading while loading === false.


When styled components generate a random class name, it may cause a hydration error when the class name changes between server and client. To solve this, you can add a configuration option in next.config.js.

// next.config.js
module.exports = {
  compiler: {
    // Enables the styled-components SWC transform
    styledComponents: true
  }
}

Referenced from this answer:

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

Retrieve the reference to the plugin object from the element where the plugin is currently active

Take a look at the code below. I've implemented a jquery plugin called myPlugin to modify the UI of #targetElement. var myPluginVar = $('#targetElement').myPlugin(); I have created a button and attached a click event listener to it. $(&ap ...

Global Path in Helmet Content Security Policy is not functioning as expected

I recently implemented Helmet to establish content security policies for my web application using Express in the backend. The specific policies are as follows: const express = require("express"); const app = express(); const helmet = require('helmet&a ...

Issue with redirect using Node.js promise

I’ve created a settings page where users can add and remove filters. To handle the deletion process, I’ve implemented this jQuery function: $('#delete-filter').click(function (e) { var filtername = $('#filter-list').val(); ...

What is the process for exporting Three.js files to .stl format for use in 3D printing?

I stumbled upon a page with this link: Is it possible to convert Three.js to .stl for 3D printing? var exporter = new THREE.STLExporter(); var str = exporter.parse(scene); console.log(str); However, despite using the code provided, I am unable to export ...

Display a specific paragraph inside a div using jQuery

I am having trouble getting my jQuery code to display a specific paragraph when a particular div is clicked on. My goal is for the content "v" to be displayed if the user clicks on the ".Virus" div, and for the contents of ".screenInfo" to be shown if the ...

Explore additional sub-categories by clicking on them with the help of jQuery or alternate techniques

I am currently working on a Magento store that has Categories with an overwhelming amount of sub-categories, taking up almost half of the page. I want to enhance user experience by implementing a feature that displays a "Load more" button when there are mo ...

Iterate through an HTML table and transfer matching items along with their corresponding calculated amounts to a separate table

<html> <body> <div> <table border="1" id="topTable"> <thead> <th>Item</th> <th>Sold</th> </thead> <tbody id="topTableBody"> <tr> ...

React DnD now enables dragging an entire list of cards instead of just a single card

Implementing react DnD in my react Project has been challenging. In the render method, I have defined a variable called Populate that generates a list of cards as shown below: render() { var isDragging = this.props.isDragging; var connect ...

Overflow of content within a rectangular element

One challenge I'm facing is creating HTML/CSS code that automatically adjusts the website layout (blocks and content) when I resize the browser window. For example: I encounter text overflow issues in a block I've created when I minimize the brow ...

Guide to creating a CSS horizontal line with square elements on either side of a title

I am currently working on how to create a horizontal line with small squares on each side of an h1 title. I have managed to achieve the horizontal line using code from a similar question, but I am struggling to add the square elements to the design. https ...

What is the process for displaying the current bitcoin price on an HTML page using API integration?

I'm looking to develop an application that can display the current Bitcoin price by fetching data from the API at . I want to showcase this information within an h2 element. Any suggestions on how I could achieve this? Thank you in advance. const e ...

Having Numerous HTML Tables All in One Page Accompanied by Written Content

I used to have a webpage with multiple (4) HTML tables all contained within one div that spanned the entire page, serving only as an indicator for the tables' starting point. It all worked perfectly until a recent Chrome update caused chaos with the t ...

The scrollbar is shifting the page's content towards the left

As a first-time user of Bootstrap, I have encountered an issue while building my website that I cannot seem to solve. Whenever I add large content that requires a scrollbar in the browser, the entire page shifts to the left. In simpler terms, when a scrol ...

Issues with Google Chrome truncating the end of lengthy pages

While working on a website project, I encountered an issue with Chrome where loading a lengthy page results in a strange box covering the bottom portion of the content. Interestingly, the same pages appear fine on Safari and Firefox, indicating that the pr ...

Trouble ensues with integrating Magic CSS3 animations via jQuery due to malfunctioning

I've been experimenting with some magical CSS classes from a source I found online (http://www.minimamente.com/magic-css3-animations/) and trying to apply them using jQuery on mouseenter and mouseleave events. Unfortunately, it's just not working ...

Unable to place an absolutely positioned Div within relative parent containers

After applying the id "enterGame" with position: absolute, I noticed that the div disappears. Even when I tried adding position: relative to the body or html tag, the div remained invisible. The relevant code snippet is as follows: html { height: 10 ...

React Nested State Object Update Causes Other Values to Disappear

I've researched and attempted various solutions to this issue, but none have proven successful. Whenever I try to update the nested login object below using the DropDown, it ends up clearing out all the other values entered into the Login object. This ...

Angular Navbar-Toogle Not Functioning with Bootstrap 5

I encountered an error on my console related to Popper.js. Specifically, I am receiving the following error message: "scripts.js:7 Uncaught SyntaxError: Unexpected token 'export'." Due to this error, I suspect that my toggle button is not functio ...

Tips for sending a string from the state of a React component to an external Python script

My journey into ReactJS and web development is just beginning. I am currently working on a web application where users can input mathematical expressions as strings. Upon submitting the input, I intend to process it using a Python script and display the o ...

Tips for preventing key/id issues in ReactJS and effectively passing props down from parent to child components

I keep encountering an obstacle when attempting to pass parent data down to the child component. Here is how I am approaching it: <%= react_component 'Items', { data: @items } %> Within my Items component, I make an ajax call, set state, ...