React.js ライブラリ「react-toastify」を使用してアラート機能を実装する
- 作成日 2020.03.12
- 更新日 2020.07.22
- React
- react-toastify, React.js, ライブラリ, 使い方

ライブラリ「react-toastify」をインストールすると、アラート機能の実装が簡単に可能です。ここでは、react.jsで downshift を利用するための手順と簡単な使い方を記述してます。
環境
- OS CentOS Linux release 8.0.1905 (Core)
- node V12.13.1
- npm 6.14.2
- React 16.13.0
react.js環境構築
下記のコマンドで構築してます。ここでは、react-appという名前でプロジェクトを作成してます。
create-react-app react-app
react-toastifyインストール
作成したプロジェクトに移動して、インストールします。
## 作成したプロジェクトに移動
cd react-app
## インストール ここではmaterial-uiも利用します
npm install react-toastify @material-ui/core
react-toastify使い方
srcディレクトリにsample.jsと名前で下記のコードを記述します。
import React, { Component } from 'react';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import Button from '@material-ui/core/Button';
class Sample extends Component {
notify = () => toast("アラート!!");
render(){
return (
<div>
<Button variant="contained" color="primary" onClick={this.notify}>通知</Button>
<ToastContainer />
</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にアクセスすると、アラート機能が実装されていることが確認できます。

-
前の記事
React.js MATERIAL-UIを使用してみる 2020.03.12
-
次の記事
CentOs8 php7.4をインストールする 2020.03.12
コメントを書く