Thought leadership from the most innovative tech companies, all in one place.

How to Create a Page Load Animated Loader in React

image

Create a react page load loader

We’re going to see how to create an animated loader that comes at the time of page load.

Basically, it’s equivalent to JavaScript’s load event. The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images.

window.addEventListener("load", (event) => {
  console.log("page is fully loaded");
});

We need to add our loaders HTML and CSS inside the index.html file present inside the public directory.

<div id="root">
  <div class="loader-wrapper">
    <div class="loader"></div>
  </div>
</div>

Since the react app is mounted in root div, so we need to add our loader HTML part inside the root div.

Then, we can add the CSS part inside the same file, inside the <style> tag.

<head>
  <style>
    body {
      margin: 0;

      padding: 0;

      height: 100%;
    }

    .loader-wrapper {
      width: 100%;

      height: 100%;

      position: fixed;

      top: 0;

      left: 0;

      background-color: #0b0b0b;

      display: grid;

      place-items: center;
    }

    .loader {
      border: 16px solid #e3e3e3;

      border-top: 16px solid #3498db;

      border-radius: 50%;

      width: 140px;

      height: 140px;

      animation: spin 1s linear infinite;
    }

    @keyframes spin {
      0% {
        transform: rotate(0deg);
      }

      100% {
        transform: rotate(360deg);
      }
    }
  </style>
</head>

And that’s it, it’ll create a page loader for your React application which will only come up whenever the website is first opened up.

It is quite different from the one which we use in the case of React.lazy and Suspense because in that, it uses the fallback property of Suspense which is visible every time the route of our page changes and it’s a new route.

Source code of the application — react-page-loader.




Continue Learning