COVID19 Lockdown Dev Log – Day 15, React Loading Screen

What I Worked On

Adding a loading screen “the right way” with React.

What I Learned

Doing it the “right way” ended up costing me most of the day just browsing through Stack Overflow and other blog posts about how you add a loading screen for your project. Usually it’s done when you want to display something to the user while your app is fetching data in the background.

For now, I agreed with myself that I’ll keep it simple and then refactor it according to “best practices” later. The implementation so far involves a ‘loading.js’ component that is used in my ‘index.js’. The loading component is, as mentioned, rather simple:

// loading.js

import React, { Component } from "react";


class Loading extends Component {
    constructor(props) {
        super(props)
        this.state = {
            isLoaded: false,
        }
    }

    render() {
        return (
            <div className="loading has-text-centered">
                <h1 className="title has-text-white">Loading. . .</h1>
            </div>
        )
    }
}

export default Loading;

Then I just import it and use it in ‘index.js’:

// index.js

import Loading from "../components/loading/loading";

export default class Index extends Component {
    constructor(props) {
        super(props)
        this.state = {
            isLoading: true,
            loadDuration: 3000
        }
    }

    componentDidMount() {
        setTimeout( () => {
            this.setState({isLoading: false})
        }, this.state.loadDuration)
       
    }

    render() {
        const { data } = this.props;
        
        if(this.state.isLoading) {
            return <Loading />
        }

Now you might be wondering “why does your ‘loading.js’ component have a state?”. Well, at first I thought much of the functionality should be in the component itself (unmounting itself, how long it should “load” then dissappear, etc.) but it turns out that it’s much easier to have the functionality in the parent component (‘index.js’). Whether that is the best way to do it or not I am unsure of, but it’ll do for now 😀 In the end, I still have some areas in React that I seem to not fully grasp yet, but I’ll get there 😀

What Distracted Me During The Day

  • Phonecalls
  • Twitch