I've been lately looking for some tricks to add a custom loading spinner to gatsby website without using the nProgress plugin that gatsby provide in the documentation, neither using the gatsby-browser.js
file and calling browser Api's such as onRouteUpdate
and onInitialClientRender
, after trying few approaches the best one that performs as expected is made by useEffect
hook, so here is the way to do that :
Prepare your svg
spinner :
you can pick one from the examples provided in this link , copy it's code and create a file loadingSpinner.svg
inside your assets file, and past the code there .
Create a file Loader.js
:
in this file import your svg
spinner and create a loader component :
import loadingSpinner from "assets/loadingSpinner.svg"
function Loader (){
return (
<div style={{
position : "fixed",
display : "flex",
width : "100vw",
height : "100vh",
justifyContent : "center",
alignItems : "center",
zIndex : 600,
backgroundColor : "#FFF"
}}
>
<img src={loadingSpinner}
alt="loader"
width="150px"
height="150px"
/>
</div>
)
}
export default Loader
Note : you can change the color and size of the spinner in the
svg
file .
Add the Loader to html.js
file:
import the Loader component in your html.js
file, and put it inside a div
tag just below the opening body
tag, and give that div
an id :
<div id="full-page-loader">
<Loader />
</div>
at this point, the loader component will be displayed permanently whenever you run the website, we will figure this out in the next step .
Control the Loader component:
in the Layout.js
file, get the loader component by it's id inside a the useEffect
hook and delete it when the Layout file get rendered, just like this :
useEffect(() => {
try {
const element = document.getElementById("full-page-
loader")
if (element) element.parentNode.removeChild(element)
} catch(error) {
console.log(error)
}
})
Note : we must use
try catch
block, so we can test our code while it's being executed, using just a normal if statement won't work and it will return a property of null error either forparentNode
or theremoveChilde
method .
Top comments (1)
I dont know if is just me, but the useEffect method its not triggered at all ?