How To Create A Simple Loading Screen Using React

How To Create A Simple Loading Screen Using React

A few days ago I made a post showing you how to create loading screens using Vue. Today, we are going to do the same, but using React!

As I said in the previous post, loading screens are always welcome, users don't want to stare at a blank screen while the page is loading.

The way I'm going to show you how to do it is very simple, but the first thing we need is a loading GIF or animation, this time I'm going to use the one that comes with Material-ui (It's really simple to install and to use, but if you need any help let me know)

Once we have it installed, we are ready to go. In my case, I have to fetch some data from an API using axios:

const [data, setData] = useState([])

useEffect(() => {
    axios
      .get("https://www.aRandomAPI.com")
      .then((response) => {
            setData((data: any) => [...data, req.data])
      })
      .catch(function (error) {
        ...
      })
  }, [])

We get the idea right? We retrieve the data and assign it to a variable. But what if the data is huge? What if the internet connection of our user is not that fast? That's why we need the loading screen.

First, let's import the circular progress that we talked about before:

import CircularProgress from '@material-ui/core/CircularProgress'

Then, on the return, before showing anything to our user, we need to check whether if our array with the data is loaded or not. One way of doing it would be checking if the length is greater than 0.

// App and App-header are classes that comes with "create-react-app"
  return (
    <div className="App">
    <header className="App-header">
       {optionsNames.length > 0 ?
           <div>
             Show your data here!
           </div>
         : <div>
             <p>Loading...</p> <CircularProgress /> 
           </div>      
       }
     </header>
   </div>
 );

We would end up with something like this:

Example gif

Simple enough, right? And this works with any kind of data that you need to show, which is great. I used this method on my first React app, you can check it out.

Anyway, thanks for reading, hope you liked it!


See more at: blog.daviddiazh.dev

Check out my first React App: guessthesubredd.it