【react-loading】Reactのローディングライブラリを導入する

本記事では、Reactのローディングライブラリである【react-loading】を導入する手順について紹介したいと思います。

デモ

※静止画ですみません。

導入手順

1.インストール

npm

npm i react-loading

2.ローディング用コンポーネントを作成する

ローディング用のコンポーネント例です。

  • Reduxを使用しているため、ローカルステートではなく、ストアーからローディングのフラグ(isLoding)と表示するテキスト(loadingText)を取得して使用
  • isLoadingがtrueならローディングコンポーネント(<ReactLoading/>)を描画し、falseならchildrenを描画するようにしています。(childrenは/resources/js/index.jsで記載している<App/>コンポーネントを指しています)

/resources/js/components/common/Loading.jsx

import React from "react";
import ReactLoading from "react-loading";
import { useSelector } from "react-redux";
import { getIsLoading, getLoadingText } from "../../reducks/loading/selectors";

const Loading = ({ children }) => {
  const selector = useSelector((state) => state);
  const isLoding = getIsLoading(selector);
  const loadingText = getLoadingText(selector);

  if (isLoding) {
    return (
      <section className="flex justify-center items-center h-screen">
        <div>
          <ReactLoading
            type="spin"
            color="#ebc634"
            height="100px"
            width="100px"
            className="mx-auto"
          />
          <p className="text-center mt-3">{loadingText}</p>
        </div>
      </section>
    );
  } else {
    return <>{children}</>;
  }
};

export default Loading;

3.ローディング用コンポーネントでApp.jsxをラッパーする

エントリーポイント用のindex.jsの例です。
<Loading></Loading>で<App/>を包んであげることで、上述の通り、<Loading/>コンポーネント内で<App/>をchildrenとして受け取ることができます

/resources/js/index.js

※Reduxに関する記述は割愛

import App from "./App";
import Loading from "./components/common/Loading";

if (document.getElementById("root")) {
  ReactDOM.render(
    <Loading>
      <App />
    </Loading>
    document.getElementById("root")
  );
}

ローディングアイコンのカスタマイズ

1.プロパティ

以下の通りです。

NameTypeDefault Value
typeStringballs
colorString#ffffff
delayNumber0 (msecs)
heightNumber or String64 (px)
widthNumber or String64 (px)
classNameString''

2.ローディングアイコンの種類

以下の8種類が設定可能です。

  • blank
  • balls
  • bars
  • bubbles
  • cubes
  • cylon
  • spin
  • spinningBubbles
  • spokes

コメント

タイトルとURLをコピーしました