DEV Community

Cover image for How to create a page load animated loader in React
GermaVinsmoke
GermaVinsmoke

Posted on

How to create a page load animated loader in React

We’re gonna 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');
});
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)