LoginSignup
64
65

【React / Next】gifを使わずにcssだけでオーバーレイスピナー(loading)を実現する

Last updated at Posted at 2022-08-22

個人的な備忘録です。

環境

  • react: 17.0.2
  • next: 11.1.3
  • sass: 1.47.0

やりたいこと

  • ローディング中は Overlay Spinner を表示させて画面操作ができないようにする
  • gifなどの画像は使用せずに、cssだけでスピナーを実装する

完成イメージ

spinner.gif

スピナーの実装

OverlaySpinner.tsx
import styles from './overlaySpinner.module.scss';

export const OverlaySpinner = () => {
  return (
    <div className={styles.overlay}>
      <div className={styles.spinner}></div>
    </div>
  );
};
overlaySpinner.module.scss
.overlay {
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background: black;
  opacity: 0.5;
  z-index: 999;
}

.spinner {
  position: absolute;
  left: 50%;
  top: 50%;
  height: 60px;
  width: 60px;
  margin: 0px auto;
  -webkit-animation: rotation 0.6s infinite linear;
  -moz-animation: rotation 0.6s infinite linear;
  -o-animation: rotation 0.6s infinite linear;
  animation: rotation 0.6s infinite linear;
  border-left: 6px solid rgba(0, 174, 239, 0.15);
  border-right: 6px solid rgba(0, 174, 239, 0.15);
  border-bottom: 6px solid rgba(0, 174, 239, 0.15);
  border-top: 6px solid rgba(0, 174, 239, 0.8);
  border-radius: 100%;
  z-index: 999;
}

@-webkit-keyframes rotation {
  from {
    -webkit-transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(359deg);
  }
}
@-moz-keyframes rotation {
  from {
    -moz-transform: rotate(0deg);
  }
  to {
    -moz-transform: rotate(359deg);
  }
}
@-o-keyframes rotation {
  from {
    -o-transform: rotate(0deg);
  }
  to {
    -o-transform: rotate(359deg);
  }
}
@keyframes rotation {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(359deg);
  }
}

使用時のサンプルコード

formComponent.tsx
import { OverlaySpinner } from '@/components/overlaySpinner';
import { useState } from 'react';

const FormComponent = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [filesToUpload, setFilesToUpload] = useState<File[]>();
  // 省略

  const handleUpload = async () => {
    setIsLoading(true);
    await imageUseCase.upload(filesToUpload).finally(() => {
      setIsLoading(false);
    });
    onClose();
  };

  return (
    <>
      <button type="button" onClick={handleUpload}>
        アップロード
      </button>
      {isLoading && <OverlaySpinner />}
    </>
  );
};

参考

64
65
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
64
65