How to Add Loading Spinner Component in React.js

Loading spinners in React is considered good UI/UX practices as they inform the users that data are being loaded from an external API. Additionally, buttons must be disabled when the loading spinner is displayed to avoid multiple API calls during a fetch request.

Here are the steps to add a loading spinner component in React.

Step 1: Configure React js Project

npx create-react-app reactloader

After creating a project, switch to the project directory and type the following command to react server.

yarn start

Step 2: Define a React Component

Go to the src  >> components folder and create a new file called LoaderComponent.js. I have named this file LoaderComponent.js because the name suits this article.

You can give any name like FetchDataComponent.js or TableComponent.js if you display the data in tabular format. The point of this article is how we can display the spinner while the async request is sent and receive the data from the server.

You need to install the Axios Promise-based library to perform a network request. So, install it using the following command.

yarn add axios 

Now, axios added to your project. Write the following code inside the LoaderComponent.js file.

// LoaderComponent.js

import React, { Component } from 'react';
import axios from 'axios';

export default class LoaderComponent extends Component {
   constructor(props) {
      super(props);
      this.state = this.state = {name:'',company:'',
         blog: '',
         avatar:'',
         loading: false
       }
      }
       componentDidMount() 
       {  
         axios.get("https://api.github.com/users/KrunalLathiya")
           .then(response => {
             this.setState({
               name:response.data.name,
               company:response.data.company,
               blog: response.data.blog,
               avatar:response.data.avatar_url,
               loading: false
             });
           })
           .catch(error => {
             console.log(error);
           });
       }

   render()
   {
    let data;
    if (this.state.loading) {
      data = <img src={ require('../images/giphy.gif') } />
    } else {
      data = <div>
                <br/>
                Name: {this.state.name}
                <br/>
                Company: {this.state.company}
                <br/>
                Blog: {this.state.blog}
                <br/>
                <img src={this.state.avatar}/>
            </div> 
    }
      return(
      <div>
            {data}
       </div>
      )
   }
}

What we have done is when the componentDidMount() lifecycle method is called, the Axios library sends a network request to the Github Server.

While the request is complete, we need to show the Loader or Loading indicator that shows a user that the process is going.

So, sit tight and wait for the request to complete.

After the request is complete, we need to hide that spinner or loader and display the actual data received in the response.

The loader is displayed in the below image once you add your component to the App.js file.

React Spinner

 

Step 3: Add React Component in App.js File

// App.js
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import LoaderComponent from './components/LoaderComponent';

class App extends Component {
  render() {
    return (
      <div className="App">
        Hello AppDividend
        <LoaderComponent/>
      </div>
    );
  }
}

export default App;

React Activity Indicator Spinner Loader TutorialSimulate Async Request in Javascript

You can use the setTimeout() function to simulate an async request.

componentDidMount(){
  setTimeout(() => { 
    this.setState({loading: false})
  },2000)
}

That’s it.

6 thoughts on “How to Add Loading Spinner Component in React.js”

  1. Hi KRUNAL, I have a comment. in the line:

    this.state = this.state = {name:”,company:”,
    blog: ”,
    avatar:”,
    loading: false

    loading have to be true. right?

    because then in the resolve of promisse is when this state will change and the loader spin will disappear for render the json. tell me if I am wrong.

    Reply
      • He is not wrong.. He never said “mutate” the state, but rather it should be initialized with a true value, as the page is loading when we begin. You should call this.setState({loading: false}) after the data has been fetched.

        Reply
  2. Hey Krunal:
    In the constructor(){
    super();
    this.state={
    loading:true //to load the loader else loader pic will never displayed;
    }
    }

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.