Quick and Easy Load Spinner Tutorial for React with Hooks

Monday, November 2, 2020

First, visit loading.io where you can customize a spinner and get the code needed to create it.

Next, create a LoadSpinner component in your React project.

	project-folder
	|_src
		|_LoadSpinner
			|_LoadSpinner.js
			|_LoadSpinner.css
		|_App.js
		...

Create a functional component in LoadSpinner.js. It doesn’t need to take in any props. Then paste in the HTML for the spinner. Don’t forget to import your css as well.

import React from 'react';
import './LoadSpinner.css';

const LoadSpinner = () => (
  <div className="lds-spinner"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>
);

export default LoadSpinner;

Next, paste the css code inside LoadSpinner.css

.lds-spinner {
  color: official;
  display: inline-block;
  position: relative;
  width: 80px;
  height: 80px;
}
.lds-spinner div {
  transform-origin: 40px 40px;
  animation: lds-spinner 1.2s linear infinite;
}
.lds-spinner div:after {
  content: " ";
  display: block;
  position: absolute;
  top: 3px;
  left: 37px;
  width: 6px;
  height: 18px;
  border-radius: 20%;
  background: # cef;
}

/* 
	... there are A LOT more classes I'm leaving off for the sake of space
*/

Now you can use state to control whether or not the spinner is displayed. For this example, I’m going to create a button to toggle between a visible and hidden spinner.

import React, { useState } from 'react';
import './App.css';
import LoadSpinner from './LoadSpinner/LoadSpinner';


function App() {
  const [isLoaded, setIsLoaded] = useState(true);

  const handleIsLoadedToggle = () => {
    setIsLoaded(currentIsLoaded => !currentIsLoaded)
  };
  
  return (
    <div className="App">
      <button onClick={handleIsLoadedToggle}>
      	Toggle LoadSpinner
      </button>
      
      {isLoaded && <LoadSpinner />}
    </div>
  );
}

export default App;

In this example, I’m simply displaying a button that says “Toggle LoadSpinner”. When the button is clicked, handleIsLoadedToggle runs and isLoaded is set in state to whatever the opposite of it’s current state is.

Down in the return statement, the LoadSpinner component is displayed if isLoaded is true.

If you don’t want to use hooks, you can just add isLoaded to the state of your class component.

class App extends React.Component {
  state = {
    isLoaded: true
  }

  handleIsLoadedToggle = () => {
    this.setState(prevState => ({
      isLoaded: !prevState.isLoaded
    }))
  };

  render() {
    return (
      <div className="App" >
        <button onClick={this.handleIsLoadedToggle}>Toggle LoadSpinner</button>
        { this.state.isLoaded && <LoadSpinner />}
      </div >
    );
  }
}

Check out the code here.

This post is also available on DEV.