Create React loading component with CSS3

Loading component is a component indispensable in an application. How do you create a loading component in React app?
In this snippet, we will create it with CSS3.

Step 1: Create a file Loading.js component with the jsx codes below:

import React from "react";

import "./styles.css";

function Loading({ colors, size }) {
  let style = {
    borderTopColor: "#3498db"
  };

  if (colors && colors.length > 0) {
    style = {
      borderTopColor: colors[0] ? colors[0] : "#3498db",
      borderRightColor: colors[1] ? colors[1] : "#eee",
      borderBottomColor: colors[2] ? colors[2] : "#eee",
      borderLeftColor: colors[3] ? colors[3] : "#eee"
    };
  }

  const loadingSize = size ? size : "medium"; // medium by default
  return <div className={"loader " + loadingSize} style={style} />;
}

export default Loading;

Copy this code

In this file, we have to include a styles.css file with the css3 animation codes for loading, and we have two props when we use this component: colors, size
- colors is an array included all of position border colors: [borderTopColor, borderRightColor, borderBottomColor, borderLeftColor]
- size is the size of the loading component, there are 3 size with type is string: large, medium and small

Step 2: Create a CSS file with the CSS codes below:

 .loader {
  border-color: #eee;
  border-style: solid;
  border-radius: 50%;
  border-top-color: #3498db;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;
}

.large {
  width: 120px;
  height: 120px;
  border-width: 16px;
}

.medium {
  width: 40px;
  height: 40px;
  border-width: 8px;
}

.small {
  width: 20px;
  height: 20px;
  border-width: 4px;
}

/* Safari */
@-webkit-keyframes spin {
  0% {
    -webkit-transform: rotate(0deg);
  }
  100% {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

Copy this code


Step 3: Usage in your app

import React from "react";
import ReactDOM from "react-dom";

import Loading from "./Loading";

function App() {
  return (
    <div className="App">
      <Loading size="small" />
      <Loading size="medium" colors={["blue", null, "green"]} />
      <Loading size="large" colors={["#3498db", "red", "green"]} />
      <Loading size="large" colors={["blue", "red", "green", "yellow"]} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Copy this code


© 2019 4codev

Created with love by Sil.