1

I want to show a spinner every time someone on my site changes the page.

I tried to do it this way

import React, { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';
import "./Spinner.css"

export function Spinner() {
    const { pathname } = useLocation();
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const body = document.querySelector("body");
        body.style.overflow = "hidden";

        window.addEventListener("load", () => {
            body.style.overflow = "auto";
            setIsLoading(false);
        }, { once: true });
    }, [pathname])

    return (
        isLoading ?
            <div className="spinner-wrapper">
                <div class="spinner">
                    Loading
                    <div class="spinner-sector spinner-sector-red" ></div>
                    <div class="spinner-sector spinner-sector-blue"></div>
                    <div class="spinner-sector spinner-sector-green"></div>
                </div>
            </div>
            : ""
    )
}

But it seems that the window is already loaded and the callback function for the event listener is not invoked, but actually, my images aren't loaded, yet! I also tried to attach the event listener for the body or the root element but the result is the same.

bero
  • 69
  • 7
  • I guarantee that showing a loading spinner on every page change will be infuriating for your users... – AKX Sep 06 '22 at 13:17
  • Does this answer your question? [Display a simple loading indicator between routes in react router](https://stackoverflow.com/questions/47104208/display-a-simple-loading-indicator-between-routes-in-react-router) – Mehdi Dehghani Sep 06 '22 at 13:19
  • Yes, but I have big images to show and when the user is on the page it takes 2-3 seconds to load the images. – bero Sep 06 '22 at 13:19
  • You can show the page and use a dummy image/placeholder and replace it when the image is loaded (bind load event on the image, instead) – Mehdi Dehghani Sep 06 '22 at 13:22
  • Tried Mehdi Dehghani answer, but it didn't work because I'm using functions instead of classes – bero Sep 06 '22 at 13:31
  • How do you use `Spinner` on your other components? and how do you know window is already loaded? – Mehdi Dehghani Sep 06 '22 at 13:40
  • I put it inside BrowserRouter – bero Sep 06 '22 at 14:32
  • @MehdiDehghani Because when you enter for the first time (or refresh the page) it's working fine after that when you go to another page without refresh it's just showing the spinner and not entering the callback function for the load event. – bero Sep 07 '22 at 08:19

0 Answers0