How to display loading spinner while dom is rendering in React
In this tutorial, we are going to learn about how to display a loading spinner in react at the time of dom is rendering.
Getting started
This tutorial assumes that you already created a new react project using create-react-app cli.
First, we need to add a spinner
element to the index.html
, because react initially sends a blank html file with root element and react-scripts.
Open your index.html
file and add the following elements after the root div.
<div class="loader-container">
<div class="loader"></div>
</div>
Add the spinner css styles inside the <head>
element.
<style>
.loader {
border: 16px solid #f3f3f3;
border-top: 16px solid #3498db;
border-radius: 50%;
width: 130px;
height: 130px;
animation: spin 2s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
Showing and hiding spinner
Now, we need to show the app when rendering is completed and hide the spinner, by removing it inside the componentDidMount()
lifecycle method.
import React from 'react';
class App extends React.Component {
state = {
loading: true };
componentDidMount() {
this.fakeRequest().then(() => {
const el = document.querySelector(".loader-container");
if (el) {
el.remove(); // removing the spinner element this.setState({ loading: false }); // showing the app }
});
}
fakeRequest = () => {
return new Promise(resolve => setTimeout(() => resolve(), 2500));
};
render() {
if (this.state.loading) { return null; //app is not ready (fake request is in process) }
return (
<div className="App">
<h1>Hello React</h1>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting
industry.
</p>
<img src="https://avatars2.githubusercontent.com/u/39895671?s=400"
alt="react-icon"/>
</div>
);
}
}
export default App;
In the above code, we are making a fakeRequest
once the request is finished, we are removing the spinner from the dom and showing the app.
Output:
Displaying spinner using react hooks
Similarly, we can also display the spinner in functional components using the useEffect
hook.
import React, {useState,useEffect} from 'react';
export default function App() {
const [isLoading, setLoading] = useState(true);
function fakeRequest() {
return new Promise(resolve => setTimeout(() => resolve(), 2500));
}
useEffect(() => {
fakeRequest().then(() => {
const el = document.querySelector(".loader-container");
if (el) {
el.remove(); setLoading(!isLoading); }
});
}, []);
if (isLoading) {
return null;
}
return (
<div className="App">
<h1>Hello React</h1>
<p>
Lorem Ipsum is simply dummy text of the printing and typesetting
industry.
</p>
<img src="https://avatars2.githubusercontent.com/u/39895671?s=400"
alt="react-icon"/>
</div>
);
}