Adding a Preloader in Gatsby

Viewed 944

I have a component Preloader that is responsible for a preloader meaning this one will pop up for 2 seconds and will open a window for the page.

I want this to pop up everytime my route change for instance I visits /blog page so it must first render this or load before loading the page.

What I did is I went to the gatsby-browser.js and then called the following:

  export const onPreRouteUpdate = () => {
    return <Preloader />
  }
  

This one did not work. My code is composed of these:

import React from 'react'

 const Preloader = () => {
    return (
        <div id="loader-wrapper">
        <div id="loader"></div>
        <div className="loader-section section-left"></div>
        <div className="loader-section section-right"></div>
    </div>
    )
}

export default Preloader

And this simple script:

   /* preloader */
    setTimeout(function(){
        $('body').addClass('loaded');
        $('h1').css('color','#222222');
    }, 1000);

How can I load this everytime the route changes?

1 Answers

You should just add the <Preloader /> to your layout then use onPreRouteUpdate to hide it.

gatsby-browser.js

export const onPreRouteUpdate = () => {
    setTimeout(() => {
        document.getElementById("loader-wrapper").style.display = "none"
    }, 1000)
}
Related