softare development

React JS: Show And Hide Loading Animation on Button Click

Let’s face it: We all hate to be kept waiting, especially when we don’t have control over the waiting process.

When developing software applications, there’s a chance that users will face slow connection issues, time-consuming data fetching processes, or maybe a non-optimised code.

Whatever the issue, you want to be able to give the user feedback on what’s going on so that the user, at the very least, understands that the waiting period is not in itself a bug.

We can do that effectively in React using loading animations.

In this tutorial we shall be using Bootstrap’s spinner to show loading animation in react js.

So, let’s get started.

1. Create a React app

First, we want to create a new React app using the following command:

npx create-react-app yourAppName

2. Run the application

Next, go to your app folder and run the following command

yarn start

3. Add Bootstrap dependency

So we will add our bootstrap dependency so we can be able to use bootstrap components

yarn add bootstrap
yarn add react-bootstrap

4. Let the coding begin

Now, let us modify our App.js file as follows, and we shall be using class components

import React, { Component } from "react"; 
import 'bootstrap/dist/css/bootstrap.min.css';
import { Spinner, Button } from 'react-bootstrap';

class App extends Component {
render(){
return(
<div class="container">
 <div className="btnContainer">
       <Button variant="success">Show Loader</Button>
       <Button variant="primary">Hide Loader</Button>
       </div>
</div>
)
}
}

export default App;

Here, we created a button that will both show and hide the loading animation respectively, depending on the state of our application.

Let’s add a bit of basic styling in our App.css file, shall we?

.btnContainer {
   display: flex;
   flex-direction: row;
   justify-content: space-evenly;
   align-items: center;
   position: relative;
   top: 40vh;
 }

See what we have now:

Next, we will set our state in the constructor method and we will set our initial loading state to false.

constructor(props){
    super(props);
    this.state = {
      loading: false
    }
  }

Also, we need to create a function. This function handle the process of showing and hiding our spinner element.

   toggleLoader = () => {
     if(!this.state.loading){
       this.setState({loading: true})
     }else{
       this.setState({loading: false})
     }
  }

Let’s explain what’s going on in the above code …

Here, we have an arrow function where we are checking the state of the application. If the application is in a loading state, we want to show the animation and if not, we want to hide the animation. That’s what we’re effectively doing.

So, we would put the following code in our render() method

render(){
  return (
    <div>
       
      <div className="btnContainer">
       
    {this.state.loading ?  <Spinner style={{marginBottom:27}} animation="border"            variant="danger" /> : null }
</div>
</div>
)
}

So, here we have our spinner from bootstrap and we’re using the ternary operator to check whether or not the Spinner is loading, and that is great. But …

What About Our Button Text?

Now, here’s the thing: if our spinner is not loading, we want the text to read “Show Loader” and if it is loading, we want the text to read “Hide Loader”. So, we add the following code:

<Button onClick={() => this.toggleLoader()} variant={'primary'} size="lg">{this.state.loading? 'Hide Loader': 'Show Loader'}</Button> 

Here’s the code for the full application:

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { Spinner, Button } from "react-bootstrap";
import "./App.css";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
    };
  }

  toggleLoader = () => {
    if (!this.state.loading) {
      this.setState({ loading: true });
    } else {
      this.setState({ loading: false });
    }
  };

  render() {
    return (
      <div>
        <div className="btnContainer">
          {this.state.loading ? (
            <Spinner
              style={{ marginBottom: 27 }}
              animation="border"
              variant="danger"
            />
          ) : null}

          <Button
            onClick={() => this.toggleLoader()}
            variant={"primary"}
            size="lg"
          >
            {this.state.loading ? "Hide Loader" : "Show Loader"}
          </Button>
        </div>
      </div>
    );
  }
}

export default App;

Congrats!

React JS Bootstrap Spinner Animation

Kick-start your mobile app development project with pre-built mobile app templates

View Comments

Recent Posts

Perks of Being a Copy-Paste Developer

Why borrowing code is a skill—when you understand what you're copying. For years, "copy-paste developer"…

1 day ago

Conditionally Disable an Input Field Using React Hook Form

Interactive forms rarely keep every field active all the time. Sometimes an input should only…

1 day ago

JavaScript Temporal API

A modern JavaScript API for working with dates, times, time zones, and calendars without the…

4 days ago

Node.js Under the Hood

Understanding What Happens Behind the Scenes Node.js looks simple from the outside—you write JavaScript, call…

4 days ago

This is How You Cultivate Negative Capability

The need for absolute certainty is the greatest disease the engineering mind faces. The moment…

6 days ago

You Don’t have to become the World’s Greatest Programmer.

The software industry is one of the most competitive places to build a career. Every…

1 week ago