DEV Community

Cover image for Create a simple spinner with reactjs + styled-components
0xkoji
0xkoji

Posted on

Create a simple spinner with reactjs + styled-components

In this post, I will introduce a simple spinner that uses reactjs + styled-components.

Spinner
https://vdxkbn.csb.app/

[props]

interface SpinnerProps {
  width?: string;
  height?: string;
  borderWidth?: string;
  borderColor?: string;
  duration?: number;
}
Enter fullscreen mode Exit fullscreen mode

Actually, the main part is CSS (styled-components).
Create an animation and passing it to a created style, SpinnerBody.

The structure is quite simple.
width, height, and boarderWidth can be number or string | number. I use string because I would like to pass the value with rem or px.

const spinnerAnimation = keyframes`
from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
`;

const SpinnerBody = styled.div<SpinnerProps>`
  height: ${(p) => (p.height ? p.height : "4rem")};
  width: ${(p) => (p.width ? p.width : "4rem")};
  border: ${(p) => (p.borderWidth ? p.borderWidth : "4px")} solid #d1d5db;
  border-top-color: ${(p) => (p.borderColor ? p.borderColor : "#3b82f6")};
  border-radius: 50%;
  animation: ${spinnerAnimation}
    ${(p) => (p.duration ? `${p.duration}ms` : "800ms")} linear infinite;
`;

export const Spinner = (props: SpinnerProps) => {
  return <SpinnerBody {...props} />;
};

Enter fullscreen mode Exit fullscreen mode

Codesandbox
https://codesandbox.io/s/spinner-with-reactjs-vdxkbn?file=/src/components/Spinner.tsx

Top comments (0)