How To Create A Spinner Loader Component in React

How To Create A Spinner Loader Component in React

The Spinner Loader in React.js is a component that provides a visual indicator of an operation in progress. It shows users that something is loading or that operation is taking place. Spinner Loader usually appears at the centre of the page, providing a focal point for users to focus their attention and provide feedback that something is happening.

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 Spinner Loader, as this helps users understand what is going on rather than leaving them to speculate.

Spinner Loaders are considered good UI/UX practices as they inform the users that data are being loaded from an external API or a new feature is about to show.

In this article, we will learn how to display Spinner Loader when loading an application and retrieving content from an external source, by utilizing the react-spinners library.

First, you must have known how to create a react app before the thought of integrating Spinner Loader in your project.

To learn more on how to create a react app click here.

In this article, we'll build a small application that fetches quotes, with a Spinner Loader (loading screen) while a quote is being fetched.

Let's begin by looking at our React markup.

Input:

const GenerateQuote = () => {
  return (
    <div className="container">
      <div className="loader-container" />
      <div className="main-content">
        <p>This is a demo Project to show how Spinner Loader works in React.</p>
        <div className="quote-section">
          <blockquote className="quote">
            Strong people make as many mistakes as weak people. Difference is
            that strong people admit their mistakes, laugh at them, and learn from
            them. That is how they become strong.
          </blockquote>
          <span className="author"> By: Richard Needham </span>
        </div>
        <br />
        <div className="generate">
          <button className="btn get-quote" type="submit">
            Generate Quote
          </button>
        </div>
      </div>
    </div>
  );
};

Output:

We have two <div> elements in the parent <div>(for the sake of simplicity), one has the className of loader-container where the Spinner Loader component will be, and the second has the className of main-content which will contain the quote and the button.

Integrating Spinner Loader in React Application

Installation.

To use Spinner Loader in React, we must first install the library in our project's directory by running any of the following commands:

Once that is done, we can import the Spinner Loader we want to use. You can get any React Spinner Loader from Here; Spinner Loader Collections.

In this article, we used the ColorRing Spinner Loader.

<ColorRing
  visible={true}
  height="80"
  width="80"
  ariaLabel="blocks-loading"
  wrapperStyle={{}}
  wrapperClass="blocks-wrapper"
  colors={["#e15b64", "#f47e60", "#f8b26a", "#abbd81", "#849b87"]}
/>;

This is a Spinner Loader component ColorRing for react application. The visible is a boolean (true) that determines whether the ColorRing is visible or not. If false, the ColorRing will not be rendered. The height has a type of number/string that contains the height of the ColorRing. The width has a type of number/string that contains the width of the ColorRing. The ariaLabel has a type of string "blocks-loading" that is used for the ariaLabel attribute in the wrapper element. The wrapperStyle is an object style to be applied to the wrapper. It should be a valid CSS object. It can be used for custom styling to override the default style. The wrapperClass which is a string "blocks-wrapper" is a className to be applied to the wrapperClass. It can be used for custom styling. It will override the default style. The colors which is an object, contains an array of colours to be used in the ColorRing.

Output

Full implementation

import React, { useState, useEffect } from "react";
import { ColorRing } from "react-loader-spinner";
import "./style.css";

const GenerateQuote = () => {
  const [loading, setLoading] = useState(false);
  const [quote, setQuote] = useState({});

  useEffect(() => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 1000);
  }, []);

  const getRandomQuote = () => {
    setLoading(true);
    fetch("https://api.quotable.io/random")
      .then((res) => res.json())
      .then((data) => {
        setLoading(false);
        setQuote(data);
      });
  };
  return (
    <div className="container">
      {loading ? (
        <div className="loader-container">
          <ColorRing
            visible={true}
            height="80"
            width="80"
            ariaLabel="blocks-loading"
            wrapperStyle={{}}
            wrapperClass="blocks-wrapper"
            colors={["#e15b64", "#f47e60", "#f8b26a", "#abbd81", "#849b87"]}
          />
        </div>
      ) : (
        <div className="main-content">
          <p>
            This is a demo Project to show how Spinner Loader works in react.
          </p>
          <div className="quote-section">
            <blockquote className="quote">{quote.content}</blockquote>
            <span className="author"> By: {quote.author}</span>
          </div>
          <br />
          <div className="generate">
            <button className="btn get-quote" onClick={getRandomQuote}>
              Generate Quote
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default GenerateQuote;

React Hooks were imported (useState and useEffect), followed by {ColorRing } gotten from react-spinner-loader and style.css was used for styling the User Interface (UI).

UseState was used to control the Spinner Loader on when to load and to display the result gotten from Quotable API.

The useEffect was used to setTimeout of 1000 milliseconds. This is the time Spinner Loader has to load before the result from the Quotable API mounts. For more understanding of React hooks, read React Hooks Documentation here.

Promises were used to fetch data/quotes from the Quotable API.

Inside the return, we have a ternary operator which was used for a conditional statement which is; when the button Generate Quote is clicked, it will invoke/call the function getRandomQuote, which triggers the quotable API to generate a random quote as the user waits for the result because it's coming from an external source, the Spinner Loader engages the users and keeping their attention with a Spinner Loader.

.main-content {
  margin-top: 10%;
  text-align: center;
}

.quote-section {
  border: 2px solid black;
  background: black;
  color: aliceblue;
}

.generate {
  padding-left: 2rem;
}

.get-quote {
  padding: 1rem;
  border-radius: 8px;
  cursor: pointer;
}
.get-quote:hover {
  background-color: aquamarine;
}

.loader-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  background: rgba(0, 0, 0, 0.834);
  z-index: 1;
}

The above code is the CSS that was used to style the UI.

Sample:

View the full project from this live demo.

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

Conclusion

This guide shows how to use the react-spinners library to add a Sipinner Loader to a React project.