Download How to Create a Loading Animation in React with react-spinners - JavaScript
Categories:Viewed: 44 - Published at: 4 months ago

Introduction

When creating React applications that fetch content from external sources that take some time to load, it is always a good idea to provide a pleasant user experience by engaging users and keeping their attention with a loader, as this helps users understand what is going on rather than leaving them to speculate.

In this guide, we will learn how to display loader animation when loading an application and retrieving content from external sources, by utilizing the react-spinners library.

To that end - we'll build a small application that fetches quotes, with a loading screen while a quote is being fetched: react-loading-animation-example

If you'd like to learn more about creating spinners from scratch, read our "How to Create a Loading Animation in React from Scratch"!

Creating a Sample React App

Let's begin by looking at our React markup. Basically, we have two <div> elements in the parent <div> (for the sake of simplicity) - one is the loader-container and the second is the main-content:

import React from 'react';

const App = () => {
  return (
    <div classname="container">


      <div classname="main-content">
        <h1>Hello World!</h1>

          This is a demo Project to show how to add animated loading with React.

        <div classname="buttons">
          <button classname="btn">
            <a href="#">Read Article</a>
          </button>
          <button classname="btn get-quote">
            Generate Quote
          </button>
        </div>
        <div classname="quote-section">
          <blockquote classname="quote">
            If you do not express your own original ideas, if you do not listen
            to your own being, you will have betrayed yourself.
          </blockquote>
          - <span classname="author">Rollo May</span>
        </div>
      </div>
    </div>
  );
};

export default App;

So far, we've only created a <div> for our loader. Now, let's see how we can add it and trigger it when some content loads.

Note: You can check out this repository and cross-check the code if need be while reading this guide.

Using React Spinners in Our Application

react-spinner is a collection of many spinners that we can use in our React applications. To use React spinner, we must first install the library in our project's directory by running any of the following command:

$ npm install --save react-spinners
// Or
$ yarn add react-spinners

Once that is done, we can now import the particular loader we want to use (in this case, a ClipLoader) and set some styling like size and color:

import React, { useState, useEffect } from 'react';
import ClipLoader from 'react-spinners/ClipLoader';

const App = () => {
  const [loadingInProgress, setLoading] = useState(false);



  return (
    <div classname="container">
      {loadingInProgress ? (

      ) : (
        <div classname="main-content">
          <h1>Hello World!</h1>

            This is a demo Project to show how to add animated loading with
            React.

          <div classname="buttons">
            <button classname="btn">
              <a href="#">Read Article</a>
            </button>
            <button classname="btn get-quote" onclick="{getRandomQuote}">
              Generate Quote
            </button>
          </div>
          <div classname="quote-section">
            <blockquote classname="quote">{quote.content}</blockquote>-{' '}
            <span classname="author">{quote.author}</span>
          </div>
        </div>
      )}
    </div>
  );
};

export default App;

The react-spinner library has a lot of useful features, for example, we can use it to handle loading without using ternary operators:

<cliploader color="{'#fff'}" loading="{loadingInProgress}" size="{150}">

</cliploader>

Instead of using ternary operator to display the content based on the value of the loadingInProgress variable, we've simply used loading={loadingInProgress} instead. We can also alter the CSS used to control the spinner-icon by using an override attribute:

import { useState } from "react";
import { css } from "@emotion/react";
import ClipLoader from "react-spinners/ClipLoader";

const override = css`
  display: block;
  margin: 0 auto;
  border-color: red;
`;

function App() {
  let [loadingInProgress, setLoading] = useState(true);

  return (
    <div classname="container">
      <cliploader color="{'#fff'}" loading="{loadingInProgress}" css="{override}" size="{150}">

    // ...
    </cliploader></div>
  );
}

export default App;
Note: We can read more about react-spinner in the documentation, where we can see a list of available sinners as well.

Conclusion

In this short guide, we've taken a look at how you can use react-spinners to add a loading spinner to an element in React.

Reference: stackabuse.com