Generally, an API takes time to return the response. It depends upon the server configuration and the data size. While fetching the data through API the screen goes blank until the response shows. It is not a good user experience for real-world applications. There can be possibilities that the user will change the screen or refresh the page. Sometimes the user can go off the website. There must be something in the website that the user will stay to that screen. So, we show an indicator to the user that data is loading. Here, we will implement the loading spinner in React JS. There are lots of npm packages available to set the loading spinner in React JS. In this post, I will show you the Bootstrap spinner in React JS. React Bootstrap loader is very simple and easy to implement. So, let’s do that quickly.
Prerequisites
Before moving to this post, I assume, you are familiar with the following-
- React JS core
- React Router DOM
- Axios For API Handling
For creating a React JS application, you will require Node.js installed in your system. When you are ready, let’s hit the below command to have a new application.
npx create-react-app blog
It will take a couple of minutes to install React JS inside the specified directory.
After creating the application, just navigate to the application folder and run it.
cd blog
npm start
It will start the development server of React Application. In the browser, you will be having the homepage of React JS.
Here, you have the React JS application ready. Now, it’s time to create React loading spinner using Bootstrap. But, before that, you need the Bootstrap package installed in the application.
File Upload in React JS Using Laravel 8 RESTful API
Install Bootstrap in React JS
To install the React bootstrap package, just visit the official site of React Bootstrap. You will have the below page. So, simply click on the Get started button. You will have the command to install the React Bootstrap.
Now, in the terminal just hit the command as showing below.
npm install react-bootstrap bootstrap@5.0.2
This will add the Bootstrap dependency inside your React JS application.
For API requests handling, we will be using the Axios library. So, also, you will have to install the Axios here.
npm i axios
Now, you are good to go for creating components and for API response handling.
How to Use Axios in React JS For API Requests Handling
Create Component in React For Loading Spinner
For applying the loading spinner in React, I will set it with the API response. In the last post of React JS, I have shown you the use of the Axios library for HTTP requests handling in React.
Here, I am creating a Posts.js component for fetching the posts using the fake API. So, after creating the component, let’s put the below snippet there.
import React, { Component } from "react";
import axios from "axios";
export default class Posts extends Component {
constructor(props) {
super(props);
this.state = {
posts: [],
message: "",
};
}
componentDidMount() {
// GET request
this.fetchPosts();
}
// fetch all post using GET request
fetchPosts = () => {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then((response) => {
if (response.status === 200) {
this.setState({
posts: response.data,
});
}
})
.catch((error) => {
console.log(error);
});
};
render() {
return (
<div className="container-fluid py-3">
<div className="card">
<div className="card-header">
<h4 className="card-title font-weight-bold text-center"> API Request Handling in React Using Axios </h4>
</div>
<div className="card-body">
<div className="row">
<div className="col-xl-4 col-lg-4 col-sm-4">
<h5 className="font-weight-bold">GET Request - Fetch Posts</h5>
</div>
<div className="col-xl-4 col-lg-4 col-sm-4">
<span className="text-success">
{this.state.message ? this.state.message : ""}
</span>
</div>
<div className="col-xl-4 col-lg-4 col-sm-4 text-end">
<button className="btn btn-primary"> Create Post </button>
</div>
</div>
<table className="table table-bordered my-3">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
{this.state.posts.length > 0 ? (
this.state.posts.map((post) => (
<tr key={post.id}>
<td> {post.id} </td>
<td> {post.title} </td>
<td> {post.body} </td>
</tr>
))
) : (
<tr>
<td colSpan="4">
<h5 className="text-danger text-center">No post found</h5>
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
);
}
}
After creating the route for the above component, you will be having the result as showing below.
Here, we have the data in the response. But, while fetching the data, it takes a time of milliseconds.
So, here we will fill this gap with a React bootstrap loader.
Form Handling in React JS With Validation Using React State
Apply Loading Spinner in React JS
React Bootstrap provides the spinner component. So, firstly, you will need to import the spinner component at the top.
import Spinner from "react-bootstrap/Spinner"
After that, we will define a state for the loader. The initial state will be false for the loading as showing below.
this.state = {
posts: [],
message: "",
loading: false,
};
- Now, in the fetchPosts() function, we will set it to true at the very first. So, that when the function will call the loading state will become true.
- After getting the API response, again the loading state will become false.
That’s the logic for applying the React bootstrap loading spinner.
fetchPosts = () => {
this.setState({ loading: true });
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then((response) => {
if (response.status === 200) {
this.setState({
posts: response.data,
loading: false,
});
}
})
.catch((error) => {
console.log(error);
});
};
Now, it’s time to display the React loading spinner on the basis of the condition at the table area.
{this.state.loading ? (
<tr>
<td rowSpan="4" colSpan="4">
<div className="text-center py-5">
<Spinner animation="border" />
</div>
</td>
</tr>
) : this.state.posts.length > 0 ? (
this.state.posts.map((post) => (
<tr key={post.id}>
<td> {post.id} </td>
<td> {post.title} </td>
<td> {post.body} </td>
</tr>
))
) : (
<tr>
<td colSpan="4">
<h5 className="text-danger text-center">No post found</h5>
</td>
</tr>
)}
- In the above snippet, I have checked the state of loading spinner. If it is true then spinner component is displaying. Otherwise, the table content will be displaying.
So, the final snippet of the component will look like this –
import React, { Component } from "react";
import axios from "axios";
import Spinner from "react-bootstrap/Spinner";
export default class Posts extends Component {
constructor(props) {
super(props);
this.state = {
posts: [],
message: "",
loading: false,
};
}
componentDidMount() {
// GET request
this.fetchPosts();
}
// fetch all post using GET request
fetchPosts = () => {
this.setState({ loading: true });
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then((response) => {
if (response.status === 200) {
this.setState({
posts: response.data,
loading: false,
});
}
})
.catch((error) => {
console.log(error);
});
};
render() {
return (
<div className="container-fluid py-3">
<div className="card">
<div className="card-header">
<h4 className="card-title font-weight-bold text-center"> API Request Handling in React Using Axios </h4>
</div>
<div className="card-body">
<div className="row">
<div className="col-xl-4 col-lg-4 col-sm-4">
<h5 className="font-weight-bold">GET Request - Fetch Posts</h5>
</div>
<div className="col-xl-4 col-lg-4 col-sm-4">
<span className="text-success">
{this.state.message ? this.state.message : ""}
</span>
</div>
<div className="col-xl-4 col-lg-4 col-sm-4 text-end">
<Link to={"/posts/create"} className="btn btn-primary"> Create Post </Link>
</div>
</div>
<table className="table table-bordered my-3">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
{this.state.loading ? (
<tr>
<td rowSpan="4" colSpan="4">
<div className="text-center py-5">
<Spinner animation="border" />
</div>
</td>
</tr>
) : this.state.posts.length > 0 ? (
this.state.posts.map((post) => (
<tr key={post.id}>
<td> {post.id} </td>
<td> {post.title} </td>
<td> {post.body} </td>
</tr>
))
) : (
<tr>
<td colSpan="4">
<h5 className="text-danger text-center">No post found</h5>
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
);
}
}
Now, switch to the browser and check the result.
You may change the variants for the spinner. Bootstrap providers the different variants and animation types for the spinner component.
Brief Overview of React Routing Using React Router DOM
Final Words
I am wrapping up the post here. I assume you got the basic idea of implementing the React loading spinner in your application. You can try different variants and animations like grow. You can customize the size of the spinner as per your requirement. Using this way, you can apply the overlay for a full-page using the loading spinner. React bootstrap loader is a clean and easiest way to implement. I hope this post will helpful for you all. Thanks.
Leave a Reply