How To Add loader In ReactJS

In this article, we will learn how to add loader in our project. We will use loader in axios call.

–First, open the react project and install the below package

-npm I react-bootstrap

-npm i reactstrap

-npm i axios

–Then import this package in app.js file

import {Table} from "react-bootstrap";
import { Spinner } from 'reactstrap';
import axios from 'axios';

-Add  IsLoading usestate in  app.js file

const [IsLoading, setIsLoading] = useState(true);

In this useState , we set it as true to enable it to load the data appear.

–Then add loader like this,

{
    IsLoading &&
    <div className="loader">
    <Spinner color="white" />
    </div>
}

–Add below CSS:

.loader {
  height: 100vh;
  width: 100%;
  background: rgba(0,0,0,0.5);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 10;
}
.loader .spinner-border {
  position: absolute;
  top: 40%;
  left: 50%;
}

–Add below code for Axios call:

 axios.get('http://localhost:5000/allData')//add your api call
 .then((re) => {
  setIsLoading(false)
  setData(re.data.result)
})

— After the getting response from API, we set the IsLoading state false to disappear  loader

–My App.js file looks like this:

import React, { useEffect, useState } from 'react'
import {Table} from "react-bootstrap";
import { Spinner } from 'reactstrap';
import axios from 'axios';
function Loader() {
    const [data, setData] = useState([]);
    const [IsLoading, setIsLoading] = useState(true);
    useEffect(() => {
            axios.get('http://localhost:5000/allData')//add your api call
                .then((re) => {
                    setIsLoading(false)
                    setData(re.data.result)
                })
    }, [])
    return (
        <>
            <div className="container">
                {
                    IsLoading &&
                    <div className="loader">
                        <Spinner color="white" />
                    </div>
                }
                <Table striped hover bordered>
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Name</th>
                            <th>State</th>
                            <th>Amount</th>
                        </tr>
                    </thead>
                    <tbody>
                        {data.map(ele => (
                            <tr>
                                <td>{ele.invoice_id}</td>
                                <td>{ele.name}</td>
                                <td>{ele.s_state}</td>
                                <td>{ele.amountDue}</td>
                            </tr>
                        ))}
                    </tbody>
                </Table>
            </div>
        </>
    )
}
export default Loader

output:

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories