Reactでnotificationを簡単に実装できるreact-notificationsを試してみた
Reactで簡単にnotificationを使えるライブラリを見つけた
create-react-appを使ってサクッと試してみる
npx create-react-app react-notifications-sample cd react-notifications-sample
create-react-app
でyarn start
したときに勝手にブラウザ立ち上がるのが個人的に嫌いなので、ついでに start
コマンドを下記のように書き換える。
"start": "BROWSER=none react-scripts start",
react-notificationsをインストール
yarn add react-notifications
src/App.js
を下記のように書き換える。
React NotificationsのREADME
に書かれているサンプルをそのまま取り入れつつ、書いています。
import React from 'react'; import './App.css'; import 'react-notifications/lib/notifications.css'; import { NotificationContainer, NotificationManager } from 'react-notifications'; const createNotification = type => { switch (type) { case 'info': NotificationManager.info('Info message'); break; case 'success': NotificationManager.success('Success message', 'Title here'); break; case 'warning': NotificationManager.warning( 'Warning message', 'Close after 3000ms', 3000 ); break; case 'error': NotificationManager.error('Error message', 'Click me!', 5000, () => { alert('callback'); }); break; default: console.log("Couldn't find notification type"); break; } }; export default () => { return ( <div className="App"> <button onClick={() => createNotification('info')}>Info</button> <br /> <button onClick={() => createNotification('success')}>Success</button> <br /> <button onClick={() => createNotification('warning')}>Warning</button> <br /> <button onClick={() => createNotification('error')}>Error</button> <br /> <NotificationContainer /> </div> ); };
動かしてみたサンプルが下記
READMEを軽く読んだだけでも、結構使いやすそうな気がしたので、サクッと通知をReactで実装したいときは良いかもしれない。
NotificationContainer Props
https://github.com/minhtranite/react-notifications#notificationcontainer-props
NotificationManager API
https://github.com/minhtranite/react-notifications#notificationmanager-api