Steps to display a full-page loader/spinner prior to the completion of loading a React application

What is the best way to create a full-page loader/spinner that will be displayed until a React (or other JS-based framework) app is fully loaded?

By "fully loaded," I mean when the browser's spinner stops spinning.

I have experience creating loaders/spinners for non-JS rendered websites, but I am unsure how to implement them for JS-rendered apps.

How can I determine when the root div is populated with the fully loaded React app?

Answer №1

To incorporate a loading indicator in your single page application (SPA), you can insert a loading sign within the index.html file inside a div that is typically labeled as root or app. This loading indicator will automatically disappear once the entire application has been fully loaded. For instance, include the following styling inside the head section of your index.html file:

<style>
    .loading {
        display: inline-block;
        width: 30px;
        height: 30px;
        border: 2px solid rgba(0,0,0,.2 );
        border-radius: 50%;
        border-top-color: rgba(0,0,0,.4 );
        animation: spin 1s ease-in-out infinite;
        -webkit-animation: spin 1s ease-in-out infinite;
        left: calc(50%);
        top: calc(50%);
        position: fixed;
        z-index: 1;
        }

        @keyframes spin {
        to { -webkit-transform: rotate(360deg); }
        }
        @-webkit-keyframes spin {
        to { -webkit-transform: rotate(360deg); }
        }
</style>

Next, place the following code within the body tag:

<body>
    <noscript>
        You need to enable JavaScript to run this app.
    </noscript>
    <div id="app">
        <div class="loading"></div>
    </div>
</body>

Answer №2

I encountered the same issue and found a solution that worked for me:

In my index.html:

<body
    <div id="spinner" class="container">
        <img src="src/assets/img/loader.svg" alt="loading...">
    </div>
    <div id="root"></div>
</body> 

And in my App.js:



function App() {
  
  const [loading, setLoading] = useState(true)

  const spinner = document.getElementById("spinner")

  if (spinner){
    setTimeout(() => {
      spinner.style.display = "none";            
      setLoading(false)
    })
  }

  return (
        !loading && (
        <div className="App">

        // components to be loaded.

      </div>
        )
  );
}

export default App;

Important Note: Using setTimeout() with no time specified is crucial to prevent your app from getting stuck in an infinite rendering loop. You can learn more about it here.

*

Alternatively, you can write it like this:

  // const [loading, setLoading] = useState(false)
  const loading = false
  const spinner = document.getElementById("spinner")
  if (spinner){
    setTimeout(() => {
      spinner.style.display = "none";            
      // setLoading(false)
    })
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Rearrange the position of the customized google map marker to appear just above the latitude

Can you provide guidance on how to move a customized Google Map marker above a specific latitude and longitude point? You can view the code structure in this JSBIN: Link. I have used three object arrays for reference. Where should I insert the "anchor" i ...

Implementing a Preloader in a React Web App

I am looking to implement a preloader in my React application because it takes a long time to load. I want the preloader to automatically render until all the contents of my application are fully ready to be loaded. Is it possible to achieve this? I could ...

Show the button when the mouse moves over the image

Here is the snippet of code I am working with: <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"> <script src="Js/jquery.min.js"></script> <script type="text/javascript"> $(document).r ...

Unable to activate primary error handler in my Node.js Express application

I have implemented node express (4.15.2) and used the default error handler provided by the express generator function to manage errors. Here is the code snippet: const app = express(); app.set('port', config.enviroment.portNumber); app.use(log ...

Can multiple shadow hosts utilize a common shadow DOM?

As I navigate the world of Web Components, I find myself still grappling with a full understanding of its capabilities. One thing that stands out to me is the numerous advantages it offers. A burning question in my mind is whether it's feasible to sh ...

Using the meta viewport tag effectively in a NextJS 14 application router

I am currently attempting to include the responsive viewport HTML meta tag in my root layout file (layout.tsx). My setup involves Nextjs v14 with the app/router. import Head from 'next/head' import type { Metadata } from 'next' import ...

Issue with jQuery's addClass() function not functioning properly on Internet Explorer versions 8, 9, and possibly others as well

Here is some basic HTML code: <div class="stuff-choice"> <div class="item a"> <label class="signup-checkbox"> <input type="checkbox" value="a" name="stuff[a][]" id="stuff_choice_" class="things"> <strong>A&l ...

Adjust Material UI React TableCell width based on content length

How do you dynamically set the width of a TableCell in Material UI react? I have attempted this approach, but it is not functioning as expected: return( <Paper className={classes.root}> <Table className={classes.table}> ...

Using AJAX to send data to the server in jQuery

Currently, I have an AJAX request implemented on my webpage. I am exploring methods to detect when an AJAX call is initiated within the page using jQuery or JavaScript. Is there a way to identify or trigger a function upon the initiation of an AJAX reques ...

The update feature activates upon reaching the bottom of the page, but it continues to refresh constantly

In my VueJS component, I have implemented a scroll event that triggers an AJAX call to update the Jobs() function when the user is getting close to the end of the page. if ( windowScrollTop >= (documentHeight - windowHeight - 50) ) { this.updat ...

ERROR: The specified module '../node-v11-darwin-x64/node_sqlite3.node' could not be located

Our server has a modified version of the Ghost blogging platform with updated content and design. I recently transferred the blog's app folder to my local machine and followed the provided instructions, which appeared to be straightforward. Quickstar ...

Streaming live video on the website

Hi there! I'm looking to integrate live video capturing into an HTML/JavaScript site for a presentation. However, I'm not sure where to start my search. Can anyone point me in the right direction? :) The live video will be captured by a camera o ...

Having trouble fixing the npm installation error for react-select that says "An unknown git error occurred, [email protected]: Permission denied (publickey)"?

I am encountering difficulties installing react-select for my react application. I have attempted the following commands: npm config set registry http://registry.npmjs.org npm install --save react-select However, I am encountering the following error: An ...

Could you explain the distinction between these two arrow functions?

I'm puzzled about why the second arrow function is effective while the first one isn't. //the first one doesn't function properly this.setState = () => { text: e.target.value, }; //in contrast, this one ...

Clearing HTML Text Input Box When User Presses Enter

Currently, I am working on a lengthy program that is functioning almost flawlessly. However, there is one persistent issue: whenever I hit the Enter key while the text box is clicked, it clears the box and appends the data to the URL as if it were a GET re ...

The Array Find() method keeps returning 'undefined' when trying to search for data based on URL parameters

Is there a way to display data from an array based on a specific condition? I have been attempting to do this by checking if the requested id matches any of the ids in the data array. Unfortunately, whenever I run the following code snippet, I always end u ...

Is there a way for me to view the output of my TypeScript code in an HTML document?

This is my HTML *all the code has been modified <div class="testCenter"> <h1>{{changed()}}</h1> </div> This is my .ts code I am unsure about the functionality of the changed() function import { Component, OnInit } f ...

What is the best way to link a single post to a collection of posts?

I am currently working on building a basic blog using PHP. My goal is to create a link from a post to a list of all posts on the blog, similar to the example shown below: Example of how I plan to display posts and a post viewer There are two distinct par ...

Having issues with implementing multiple checkboxes and onChange in React with Material-UI

Within an edit modal form, I have numerous checkboxes that correspond to a record structure used for updates. These checkboxes are included in the state of the form inputs. An onChange event is set up to handle these inputs. Upon clicking a checkbox, the ...

Issue with ReactJS not applying classes based on conditions

I'm currently working on toggling a class on an element when a user clicks. However, I am facing an issue where my code only sets the class for a single element and does not refresh for subsequent clicks. Even though the set class is not being removed ...