React.js Notificationを簡単に実装できるreact-notification-systemの使い方

React.js Notificationを簡単に実装できるreact-notification-systemの使い方

React.jsのライブラリreact-notification-systemを利用するための簡単なサンプルコードです。

環境

  • OS  CentOS Linux release 8.0.1905 (Core)
  • node V10.16.3
  • npm 6.9.0
  • React 16.12.0

react-notification-systemインストール

react-notification-systemをインストールします。

npm install react-notification-system

react-notification-system使い方

src配下のApp.jsを下記のように編集します。

※デザインにmaterial-ui を利用してます。利用手順はこちら

import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import NotificationSystem from 'react-notification-system';
import './App.css';

class App extends Component{
  constructor(props){
    super(props);
    this.notificationSystem = React.createRef();
    this.addNotification = this.addNotification.bind(this);
  }
  addNotification() {
    const notification = this.notificationSystem.current;
    notification.addNotification({
      //タイトル
      title: "Notification",
      //メッセージ
      message: "通知です",
      //通知タイプ(error,warning,info,success)
      level: "info",
      //消滅時間 ここでは5秒
      autoDismiss: 5,
      // tr (top right), tl (top left), tc (top center), br (bottom right), bl (bottom left), bc (bottom center)
      position: "tc",
      action: {
        label: 'Button',
        callback: function() {
          console.log('button click!');
        }
      }
    })
  }
  render() {
    return (          
      <div className="App">
        <header className="App-header">
          <Button variant="contained" color="primary" onClick={this.addNotification}>Notification</Button>
          <NotificationSystem ref={this.notificationSystem} />
        </header>
      </div>          
    )
  }
}

export default App;

ブラウザから http://プライベートIP:3000にアクセスして、「Notification 」ボタンをクリックすると、 Notificationが表示されます。