How do I add a website loading screen in ReactJS?


I’m really new to ReactJs, JS and basically all of web development. I trying to create a single page portfolio website using ReactJS and wanted to try some more advanced techniques such as using hooks. I wanted to create a simple effect where an animation plays once (when a user first logs in to my website), then they are brought to the main site. All the resources i’ve found online relate to loading screens whilst fetching data from an API. Here is my code for the loading screen:

import Typical from 'react-typical';
import "./Loading.scss";
import {useState, useEffect} from 'react';

const Loading = function Loading() {
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true)
    setTimeout(() => {
      setLoading(false)
    },18000);

  }, [])

        return (
      <div>
        <h1 id="loading">
          { loading ?  <Typical oop={1} wrapper = 'p'
          steps={[
              "Hello",
              2000,
              "My name is Leonard.",
              3000,
              "I am an aspiring developer",
              3000,
              "Welcome to my website!",
              3000,
            ]} /> : null}
        </h1>
      </div>
    );

}

I’m using a very simple react package called typical which gives a nice animation of words being typed on the screen like a typewriter, then gets deleted, then the next bit of text gets shown etc.. this only loops once. I’ve used the useState and useEffect hooks with a timer to setLoading to false in 18s which is when the animation stops. As you can see I render the animation only if loading is true, using a ternary operator, then once loading gets set to false then null gets displayed. My app.js looks like this:

import Nav from './Components/Nav';
import "./App.scss";
import Loading from './Components/Loading';

function App() {
  return (
    <div>
      <Loading /> 
      <main>
      <Nav/>
      </main>

    </div>

    
  );
}

export default App;

(Apologies for the awful JSX). The issue i’m having is that both navbar and the loading screen loads at the same time. I’m unsure how to hide all my other components until the animation is finished. Everything I try is waaay to complicated and really doesnt seem very efficient at all. I appreciate any help thank you!

Source: React – Stack Overflow

November 24, 2021
Category : News
Tags: animation | javascript | react hooks | react-component | reactjs

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.