2

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.

8
  • I guarantee that showing a loading spinner on every page change will be infuriating for your users... Commented Sep 6, 2022 at 13:17
  • 1
    Does this answer your question? Display a simple loading indicator between routes in react router Commented Sep 6, 2022 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. Commented Sep 6, 2022 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) Commented Sep 6, 2022 at 13:22
  • Tried Mehdi Dehghani answer, but it didn't work because I'm using functions instead of classes Commented Sep 6, 2022 at 13:31

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.