How to Create a Loading Animation in React with react-spinners

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:

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="loader-container">
        <div className="spinner"></div>
      </div>

      <div className="main-content">
        <h1>Hello World!</h1>
        <p>
          This is a demo Project to show how to add animated loading with React.
        </p>
        <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
Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

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="loader-container">
          <ClipLoader color={'#fff'} size={150} />
        </div>
      ) : (
        <div className="main-content">
          <h1>Hello World!</h1>
          <p>
            This is a demo Project to show how to add animated loading with
            React.
          </p>
          <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} />

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} />

    // ...
    </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.

Last Updated: June 15th, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Joel OlawanleAuthor

Frontend Developer & Technical Writer

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms