話の流れ
- 前書き
- 導入
- 使い方
- 後書き
前書き
今回React.jsでTodoを作るにあたって、通知機能をつけたいと思い、使ってみました。
シンプルにでき、そのままでも綺麗に実装されますが、通知の中もコーディングで独自のスタイルを当てられるのが、自由度があっていいと思います。
公式ではデモが見れるのでぜひ参考にしてみてください。
公式:http://igorprado.com/react-notification-system/
GitHub: https://github.com/igorprado/react-notification-system
導入
npmまたはyarnでインストールします。
npm install react-notification-system
yarn add react-notification-system
そして、サンプルコードは以下になります。
想定は、ボタンを押すと、通知が現れるというものです。(GitHubのUsingと一緒ですが...)
import React, { Component } from 'react';
import NotificationSystem from 'react-notification-system';
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: "Hi, I'm information!",
level: "info"
})
}
render() {
return (
<>
<button onClick={this.addNotification}>通知する</button>
<NotificationSystem ref={this.notificationSystem} />
</>
)
}
}
このtitleとmessageの部分をhtmlで以下のように記述することができます。
(必要な箇所だけ抜粋しています。また、スタイルにはstyled-componentsを利用しています。styled-componentsの仕様につきましては、他の記事を参照ください。)
const Notification = styled.div`
text-align: center;
button{
background: rgba(54, 156, 199, .1);
padding: 4px 1rem;
width: 80%;
border: solid 2px rgb(54, 156, 199);
border-radius: 6px;
color: rgb(54, 156, 199);
cursor: pointer;
text-align: center;
font-weight: bold;
&:hover {
background: rgba(54, 156, 199, .4);
}
}
`;
addNotification() {
const notification = this.notificationSystem.current;
notification.addNotification({
level: 'info',
autoDismiss: 10,
children: (
<Notification>
<h2>削除してもよろしいですか</h2>
<button onClick={console.log("Compolete")}>Delete</button>
</Notification>
)
});
}
ボタンもデフォルトのスタイルでよければ、childrenプロパティを用いずにactionプロパティを使えば同様に実装が可能なのですが、上の画像のように、ボタンだけでなく、自分のスタイルを使いたい!という場合は、こちらで実装してみてください。
あと、今回はやっていないですが、Font Awesomeを使ってもおしゃれになりますね!!
後書き
ページに通知機能がつくと、なんか気持ちいいですね笑
思っていたよりも簡単に実装ができたので、ご参考までに。
ありがとうございました。