React.js ライブラリ「react-hot-toast」を使ってtoastを実装する

React.js ライブラリ「react-hot-toast」を使ってtoastを実装する

ライブラリ「react-hot-toast」をインストールすると、toastを実装することが可能です。ここでは、react.jsでreact-hot-toastを利用するための手順と簡単な使い方を記述してます。

環境

  • 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

react-hot-toastインストール

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

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

react-hot-toast使い方

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

import React from 'react'
import toast, { Toaster } from 'react-hot-toast'

const notify = () => toast('Here is your toast.')

const Sample = () => {
  return (
    <div>
      <button onClick={notify}>Make me a toast</button>
      <Toaster />
    </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にアクセスすると、toastが実装されていることが確認できます。

アイコンは、以下のようにコードを変えれば使用することが可能です。

const notify = () => toast.success('TOASTを表示')
const notify = () => toast.error('TOASTを表示')

表示時間は「duration」を指定することが設定が可能です。

const notify = () => toast.error(
  "This toast is super big. I don't think anyone could eat it in one bite. It's larger than you expected. You eat it but it does not seem to get smaller.",
  {
    duration: 1000,
  }
);

アイコンを指定して利用することも可能です。

const notify = () =>
  toast('Good Job!', {
    icon: '👏',
  })

styleを適応することも、可能です。

const notify = () =>
  toast('Good Job!', {
    icon: '👏',
    style: {
      borderRadius: '10px',
      background: '#333',
      color: '#fff',
    },
  })

閉じるボタンを使用することもできます。

const notify = () =>
toast((t) => (
  <span>
    閉じるボタンを実装
    <button onClick={() => toast.dismiss(t.id)}>
      閉じる
    </button>
  </span>
));