react bootstrap 5 loading button example

React Bootstrap 5 Loading Button Example

October 21, 2022 By Aaronn

In this tutorial, we will create button loading button when click on button using Bootstrap 5 and React. We will create simple loading button and loading spinner icon button react-bootstrap components Button , Spinner and using react useState hook and useEffect in react app.

Install & Setup Vite + React + Typescript + Bootstrap 5


React Bootstrap 5 Loading Examples

1. Create simple react bootstrap loading button using react-bootstrap components Button and react useState hook and useEffect.

import React, { useEffect, useState } from 'react';
import Button from 'react-bootstrap/Button';

export default function LoadingButton() {
  const [isLoading, setLoading] = useState(false);

  function simulateNetworkRequest() {
    return new Promise((resolve) => setTimeout(resolve, 2000));
  }

  useEffect(() => {
    if (isLoading) {
      simulateNetworkRequest().then(() => {
        setLoading(false);
      });
    }
  }, [isLoading]);

  const handleClick = () => setLoading(true);

  return (
    <div className="d-flex align-items-center justify-content-center vh-100">
      <Button
        variant="primary"
        disabled={isLoading}
        onClick={!isLoading ? handleClick : null}
      >
        {isLoading ? 'Loading…' : 'Loading Button'}
      </Button>
    </div>
  );
}
react bootstrap loading button

react bootstrap loading button


2. React Bootstrap 5 spinner loading button using react-bootstrap components Button, Spinner and react useState hook and useEffect.

import React, { useEffect, useState } from 'react';
import Button from 'react-bootstrap/Button';
import Spinner from 'react-bootstrap/Spinner';

export default function LoadingButton() {
  const [isLoading, setLoading] = useState(false);

  function simulateNetworkRequest() {
    return new Promise((resolve) => setTimeout(resolve, 2000));
  }

  useEffect(() => {
    if (isLoading) {
      simulateNetworkRequest().then(() => {
        setLoading(false);
      });
    }
  }, [isLoading]);

  const handleClick = () => setLoading(true);

  return (
    <div>
      <Button
        variant="primary"
        disabled={isLoading}
        onClick={!isLoading ? handleClick : null}
      >
        {isLoading ? (
          <Spinner animation="border" role="status">
            <span className="visually-hidden">Loading...</span>
          </Spinner>
        ) : (
          'Click to load button'
        )}
      </Button>
    </div>
  );
}