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

Common Async/Await Mistakes Every JavaScript Developer Should Avoid

JavaScript's async and await keywords revolutionized asynchronous programming by making asynchronous code look and behave more like synchronous code.…

7 hours ago

PGP Encryption And How It Works

Pretty Good Privacy (PGP) is one of the most widely used encryption systems for securing emails,…

4 days ago

How To Migrate from PostgreSQL to MySQL

Database migration is one of the most challenging tasks in software engineering. While both PostgreSQL…

1 week ago

Hidden Gems Inside Modern JavaScript

Modern JavaScript isn’t just let, const, arrow functions, and promises anymore. Over the years, the language has…

1 week ago

Software Developer Pain Points Ranked: What Frustrates Developers the Most?

Software development is one of the most rewarding careers in technology, but it is also…

1 week ago

How to Print Documents in JavaScript

Printing a document in JavaScript usually means triggering the browser’s print dialog and controlling what…

2 weeks ago