No Time Dad

A blog about web development written by a busy dad

Easy React Spinner Component

Showing a spinner when a component is loading or something asynchronous is happening in the background is one of the best ways to politely ask the user to wait. I’ve create countless spinners, and used them in countless different places. It’s deeply ingrained in web development.

React makes spinner components reusable and customizable. Creating a react spinner component just requires a single div and some custom styles.

import React from 'react';

export const Spinner = ({ customStyles }) => {
  const defaultStyles = {
    border: '10px solid #f3f3f3',
    borderTop: '10px solid #3498db',
    width: '100px',
    height: '100px',
    borderRadius: '50%',
    animation: 'spin 1s ease-in-out infinite',
  };

  return (
    <div style={{ ...defaultStyles, ...customStyles }} ></div>
  );
};
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

The nice thing about this react spinner is that it’s easy to modify the look and feel. Passing in a customStyles prop is all that’s needed. If I wanted a red spinner instead of a blue one, I’d just need to add the border-top-color: red; property or overwrite the existing borderTop value in the defaultStyles object with borderTop: '10px solid red'.

<Spinner customStyles={{ borderTopColor: 'red' }}/>

Need a smaller spinner? No problem. Passing in width and height values will do the trick.

  <Spinner customStyles={{ width: '50px', height: '50px' }}/>

An important thing to note here is this react spinner relies on css animations to work. Notice that the @keyframes definition is hardcoded in the css displayed above, and it cannot be changed by any values you pass to the customStyles prop.

There are a couple reasons for this. The first major one is that react won’t accept a key value pair for keyframes in the style attribute. It just won’t work. The second reason is that there really isn’t a reason to modify the @keyframes definition, in my opinion. Maybe if you wanted the spinner to start from a different position, but I’m not sure there is a reason to make that change dynamically.