DEV Community

Cover image for How to use React-spinners | Step by Step Guide
Niraj Narkhede
Niraj Narkhede

Posted on • Updated on

How to use React-spinners | Step by Step Guide

Are you ready to add some pizzazz to your React applications? Look no further than the React Spinner! In this comprehensive tutorial, we will guide you through getting started with this dynamic and eye-catching feature. Say goodbye to boring loading screens and hello to a more engaging user experience. Let's dive in and take your React skills to the next level with the React Spinner!

How to use React-spinners Step by Step Guide

Introduction to React Spinner

React Spinner is a popular library used in web development for creating animated loading indicators, also known as spinners. Developed by Facebook, it has gained widespread adoption among developers due to its simplicity and flexibility. In this section, we will provide an overview of React Spinner and explain why it is a valuable tool to have in your web development toolkit.

What is a spinner?

A spinner is a visual indicator that informs the user that a process or task is in progress. It typically consists of an animation or rotating icon that appears on the screen while the content or page loads. Spinners are commonly used in modern websites and apps as they improve the user experience by providing feedback on the status of an action.

Why use React Spinner?

React Spinner simplifies the process of creating animated loaders with its straightforward API. It allows developers to focus on building their application's logic instead of spending time on writing complex CSS animations.

With React Spinner, you can easily customize the appearance and behavior of your spinners according to your project's needs. It provides various props and options such as size, color, speed, and type of animation for maximum flexibility.

Also, The library takes care of browser compatibility issues so that you don't have to worry about writing different code for each browser.

How does it work?

React Spinner works by rendering an SVG element with specific styles applied based on the chosen configuration options. The SVG element is then rotated using CSS animations to create the spinning effect. This approach ensures that the spinner appears crisp and smooth on all devices, including high-resolution screens.

Checkout Our Other Tutorials
75 CSS Resources for web developers
How to Use React-Dropzone for Uploading Files
How to use React-spinners | Step by Step Guide
Free HTML Template

Installing and Setting Up React Spinner

To use the React Spinner component in your project, you will first need to install it. There are several ways to do this, depending on your development environment and preferences.

1. Using npm or Yarn

The most common way to install React Spinner is through the use of a package manager like npm or Yarn. If you are using npm, run the following command in your project directory:



npm install react-spinners --save


Enter fullscreen mode Exit fullscreen mode

Or



yarn add react-spinners


Enter fullscreen mode Exit fullscreen mode

2. Importing React Spinner

Regardless of how you installed React Spinner, now it's time to import it into your project. In order for it to work properly, make sure that you also have React installed in your project.

To import React Spinner into your component, simply add this line of code at the top:



import { BarLoader } from 'react-spinners';


Enter fullscreen mode Exit fullscreen mode

3. Using Different Types of Loader

React Spinners offers different types of loaders such as BarLoader, CircleLoader, BeatLoaderetc., each with their own unique styles and animations. To use any loader type in your component, simply replace BarLoader in our previous code snippet with the name of the loader you want to use.

4. Setting Up Props

React Spinners' loaders come with a variety of customizable props, such as color, size, and loading speed. These can be passed in as props to the component when rendering it. For example:



<BarLoader color="purple" height={4} width={100} loading={true} />


Enter fullscreen mode Exit fullscreen mode

It is important to note that each loader type has its own unique set of props, so make sure to check the documentation for the specific loader you are using.

Congratulations! You have now successfully installed and set up React Spinner in your project. With this powerful tool at your disposal, you can easily add dynamic and visually appealing loading animations to your React applications.

Customization options

React Spinner is a popular library that allows developers to add loading indicators or spinners in their React applications. One of the key advantages of using React Spinner is its customizable options, which enables developers to change the appearance and behavior of the spinner according to their specific needs.

In this section, we will explore the various customization options available in React Spinner and how they can be implemented in your project.

1. color

The color prop sets the color of the spinner. You can use any valid CSS color value. Here's a simple example using a HashLoader:



import { HashLoader } from 'react-spinners';

<HashLoader color="#36d7b7" />


Enter fullscreen mode Exit fullscreen mode

In this example, the spinner color is set to a nice turquoise. Adjusting the color prop lets you easily align the spinner with your application's theme.

2. loading

The loading prop is a boolean that determines whether to display the spinner. If set to false, the spinner will be hidden. This is especially useful for conditionally showing the spinner based on data-fetching states.



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

const DataFetchingComponent = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('/api/data')
      .then(response => response.json())
      .then(data => {
        setData(data);
        setLoading(false);
      });
  }, []);

  return (
    <div>
      {loading ? <ClipLoader loading={loading} /> : <div>Data loaded!</div>}
    </div>
  );
};


Enter fullscreen mode Exit fullscreen mode

3. size

The size prop lets you change the size of the spinner. Depending on the spinner type, this may accept a single number or an object with width and height. Here's an example using BeatLoader:



import { BeatLoader } from 'react-spinners';

<BeatLoader size={15} color="#123abc" />


Enter fullscreen mode Exit fullscreen mode

In this case, each dot in the BeatLoader spinner will be 15 pixels in diameter.

Customizing Spinners with Additional Props

Some spinners available in react-spinners come with their unique set of additional props. Let's take a look at a few examples.

4. Type:
React Spinner offers three types of spinners - Audio, Ball-Beat, and Bars. These types determine how the animation for the spinner will look like. Developers can choose between these types or even create their own custom type if required.

5. Speed:
The speed at which a spinner rotates is another customizable option offered by React Spinner. By default, all spinners have a medium rotation speed, but developers can easily modify it by changing a few lines of code.

6. Delay:
Sometimes, displaying a spinner immediately after an API call might not be desirable as it may give users the impression that something has gone wrong with their request. To avoid such scenarios, React Spinner provides an option to add delay before showing the spinner.

7. Custom Icons:
React Spinner also allows developers to use custom icons instead of traditional spinning circles or bars as loading indicators. This feature adds more flexibility and creativity in designing loaders that align with your application's branding.

8. Accessibility:
Accessibility is crucial for any web application today, especially when it comes to loading indicators or spinners for users with disabilities. With React Spinner's accessibility features, developers can make sure that all users are aware when a spinner is present and provide alternative text for screen readers.

React Spinner offers a wide range of customization options, making it the go-to library for adding loading indicators in React applications. These customization options not only enhance the visual appeal of your application but also improve its user experience by providing more control over the spinner's behavior. So, don't hesitate to explore and utilize these customization options to elevate your project's loading experience.

Code examples for different types of spinners

Code examples for different types of spinners can be a useful guide when getting started with React Spinner. In this section, we will explore various code snippets for different types of spinners, including loading and progress spinners.

1. Bar Loader:



<BarLoader
  color="#36d7b7"
  height={10}
  loading
  width={60}
/>


Enter fullscreen mode Exit fullscreen mode

2. Circular Loader:



<CircleLoader
  color="#36d7b7"
  loading
  size={60}
/>


Enter fullscreen mode Exit fullscreen mode

3. FadeLoader Loader:



<FadeLoader
  color="#36d7b7"
  height={20}
  loading
  margin={-1}
  radius={3}
  width={6}
/>


Enter fullscreen mode Exit fullscreen mode

4. MoonLoader Loader:



<MoonLoader
  color="#36d7b7"
  loading
  size={62}
/>


Enter fullscreen mode Exit fullscreen mode

Real Life Example

One of the most common features in modern web development is the use of loaders or spinners to indicate that a page or component is loading. In React, this can easily be achieved by using a Loader component. A loader component is essentially a visual representation of a process happening in the background.

React offers various libraries and tools for creating loaders, such as React Spinners and React Loading. However, we will be creating our own custom loader component from scratch in this tutorial to better understand its functionality.

To begin with, let's create a new folder named components within our project directory. Inside this folder, we will create a file called Loader.js which will contain our Loader component code.

Next, we need to import the necessary modules from React. This includes the useState hook for maintaining state and useEffect hook for managing side effects.



import React, { useState, useEffect } from 'react';


Enter fullscreen mode Exit fullscreen mode

Inside our functional component declaration, we will define two variables - one for storing the current state of the loader (loading or not), and another for setting up an interval timer that will simulate a loading process.



const [isLoading, setIsLoading] = useState(false);
const [timerId, setTimerId] = useState(null);


Enter fullscreen mode Exit fullscreen mode

Now let's create two functions - one to start the loading process and another to stop it once it's completed. The startLoading function sets isLoading state to true and also sets up an interval timer using setInterval() method which executes every 500 milliseconds. Once it reaches 10 seconds (10000 milliseconds), it stops the timer using clearInterval() method and calls stopLoading function.



function startLoading() {
    setIsLoading(true);
    const id = setInterval(() => {
        if (isLoading >= 10) {
            clearInterval(id);
            stopLoading();
        }
    }, 500)
    setTimerId(id);
}

function stopLoading() {
    setIsLoading(false);
}


Enter fullscreen mode Exit fullscreen mode

Next, we need to create a useEffect hook which will call the startLoading function when the component mounts for the first time.



useEffect(() => {
    startLoading();
}, []);


Enter fullscreen mode Exit fullscreen mode

Now let's create our JSX code for the Loader component. We will use a simple div with a class of loader and set its display property based on the isLoading state.



<div className="loader" style={{display: isLoading ? "block" : "none"}}></div>


Enter fullscreen mode Exit fullscreen mode

We can import and use this Loader component in any other React component where we want to show a loader while some process is happening in the background. We can also customize the styling of our loader by adding CSS classes or inline styles to it.

Conclusion:

Using a Loader component in React is an efficient way to indicate that something is loading without having to write repetitive code. With customizing options and easy implementation, it is an essential tool for modern web development.

Top comments (0)