How to add a loading spinner to your React.js project

Harriet Bicknell
Webtips
Published in
2 min readAug 6, 2020
https://unsplash.com/photos/Kpf1seFkMEw

Recently, while creating a website that makes multiple API calls, I found that it often took several seconds for the content to load. Users expect an app’s response time to be immediate and if they do not get a response in less than a few seconds, they start to worry. We can get around this by giving the user visual feedback, such as a spinner, to reassure users that something is happening, which eases their worries.

This article is going to a step by step tutorial on how to to get a loading spinner to appear at the centre of your screen no matter what device you are on using React.js. First, make sure that you have semantic-ui-react installed using this command:

$  npm install semantic-ui-react semantic-ui-css

Then, go onto the file where you want the loader to be. In this example, I want the content to load once I have made the API fetch request and go the data from that request. So, I need the loader to render which this.state.content is false.

import React from "react";
import { Dimmer, Loader } from "semantic-ui-react";
class Webpage extends React.Component {
state = {
content: null,
};
componentDidMount() {
getContentFromAPI.then((content) =>
this.setState({
content: content
})
);
};
render() {
if (!this.state.content)
return (
<div className=”Loader”>
<Dimmer active inverted size=”massive”>
<Loader inverted>Loading</Loader>
</Dimmer>
</div>
);
return (
//whatever you want to load once you have fetched 'content'
);
};
}
export default Webpage;

Using a simple if statement in the render method means that until this.state.content actually has some content (e.g. from the API fetch, then display the loader. When this.state.content is true, then render whatever you actually want to render on that webpage.

In order to get the loader to appear at the centre of the screen no matter what device you are on, put this code in your CSS file.

.Loader {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
}

And voila! this is what the loader turns out like!

--

--