DEV Community

Syed Faran Mustafa
Syed Faran Mustafa

Posted on • Updated on

Splash Screen on Gatsby JS

If you embark on the problem to add splash screen to your gatsby website you are in the right place. I myself was trying to add splash screen to a website and had to go a lot a forums but couldn't find much of a solution in one place after finding some pieces here and there finally done that.

You let me tell you how did it

Image description

So first find a cool GIF you want to add as splash screen then add loader code, so what loader does is wrap up the image and add id which is really important as we wanted to target that loader further on.

src/loader.js

import React from "react";
import styled from "styled-components";
import BCTLoader from "../../assets/gif/BCTloader.gif";

const Loader = () => {
  return (
    <LoaderWrapper id="loader-wrapper">
      <img src={BCTLoader} alt="GIF Image" />
    </LoaderWrapper>
  );
};
export default Loader;

Enter fullscreen mode Exit fullscreen mode

then add some css to it, I like working with styled components feel free to do it with simple css

const LoaderWrapper = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #ffff;
  z-index: 9999;
  display: none;
  justify-content: center;
  align-items: center;

  img {
    width: 20vw;
  }
`;

Enter fullscreen mode Exit fullscreen mode

Add that to your layout file if you have any if you don't have that please make one so we can have a wrapper for all the pages as we don't have centralised piece like react so we probably need to add that.

src/layout.js

import React from "react";
import Header from "./Navbar";
import Footer from "./Footer";
import Loader from "./Loader";

const Layout = ({ children }) => {
  return (
    <>
      <Header />
      <main>{children}</main>
      <Footer />
      <Loader />
    </>
  );
};

export default Layout;
Enter fullscreen mode Exit fullscreen mode

Now when you are done with it we can work with gatsby-brower so we can have access to initial rendering

gatsby-browser.js


export const onClientEntry = () => {
  setTimeout(() => {
    if (document.getElementById("loader-wrapper")) {
      document.getElementById("loader-wrapper").style.display = "flex";
    }
  }, 0);
};

export const onInitialClientRender = () => {
  setTimeout(() => {
    if (document.getElementById("loader-wrapper")) {
      document.getElementById("loader-wrapper").style.display = "flex";
    }
  }, 0);
};

export const onRouteUpdate = () => {
  setTimeout(() => {
    if (document.getElementById("loader-wrapper")) {
      document.getElementById("loader-wrapper").style.display = "none";
    }
  }, 3500);
};

Enter fullscreen mode Exit fullscreen mode

That's it! Now you would have a cool looking splash screen for your app
feel free leave any comments 🙂.

Top comments (0)