React.js ライブラリ「@agney/react-loading」を使ってローディングアイコンを表示する

React.js ライブラリ「@agney/react-loading」を使ってローディングアイコンを表示する

ライブラリ「@agney/react-loading」をインストールすると、ローディングアイコンを表示することが可能です。ここでは、react.jsで@agney/react-loadingを利用するための手順と簡単な使い方を記述してます。

環境

  • OS  CentOS Stream release 8
  • node V12.16.3
  • npm 6.14.7
  • React 16.13.0

react.js環境構築

下記のコマンドで構築してます。ここでは、react-appという名前でプロジェクトを作成してます。

create-react-app react-app

@agney/react-loadingインストール

作成したプロジェクトに移動して、インストールします。

## 作成したプロジェクトに移動
cd react-app
 
## インストール
npm install @agney/react-loading

@agney/react-loading使い方

srcディレクトリにsample.jsと名前で下記のコードを記述します。

import React from 'react'
import {
  useLoading,
  Audio,
  BallTriangle,
  Bars,
  Circles,
  Grid,
  Hearts,
  Oval,
  Puff,
  Rings,
  SpinningCircles,
  TailSpin,
  ThreeDots,
} from '@agney/react-loading'

const Sample = () => {
  const { containerProps, indicatorEl } = useLoading({
    loading: true,
    indicator: <div>
      <Audio width="50" />
      <BallTriangle width="50" />
      <Bars width="50" />
      <Circles width="50" />
      <Grid width="50" />
      <Hearts width="50" />
      <Oval width="50" />
      <Puff width="50" />
      <Rings width="50" />
      <SpinningCircles width="50" />
      <TailSpin width="50" />
      <ThreeDots width="50" />
      </div>,
  });
  return (
    <div>

      <section {...containerProps}>
        {indicatorEl} {/* renders only while loading */}
      </section>

    </div>
  );
}

export default Sample;

次に、srcディレクトリ配下にあるApp.jsを下記のように編集します。

import React from 'react';
import Sample from './sample';
import './App.css';

function App() {
  const style = {
    width: "50%",
    margin: "0 auto",
    marginTop: 150,
  };
  return (
    <div className="App">
      <div style={style}>
        <Sample />
      </div>
    </div>
  );
}

export default App;

実行します。

npm start

ブラウザから http://プライベートIP:3000にアクセスすると、ローディングアイコンが表示されていることが確認できます。

色はcolorを指定すれば変更可能です。

<Audio width="50" color="#3db70f"/>
<BallTriangle width="50" color="#3db70f"/>
<Bars width="50" color="#3db70f"/>
<Circles width="50" color="#3db70f"/>
<Grid width="50" color="#3db70f"/>
<Hearts width="50" color="#3db70f"/>
<Oval width="50" color="#3db70f"/>
<Puff width="50" color="#3db70f"/>
<Rings width="50" color="#3db70f"/>
<SpinningCircles width="50" color="#3db70f"/>
<TailSpin width="50" color="#3db70f"/>
<ThreeDots width="50" color="#3db70f"/>