この記事では、 react-notifications-component (v2.0.6)の新しいリリースについて説明します。 これはReactコンポーネントであり、フル機能の通知システムを提供し、自分で通知システムを構築する時間と労力を節約します。
それをanimate.cssと一緒にインストールすることから始めましょう:
- npm install --save react-notifications-component animate.css
通知の出入り方法をアニメーション化するためにanimate.cssを使用していますが、任意のクラスベースのアニメーションライブラリを使用できます。
基本的な使用法
このライブラリは非常に機能が豊富ですが、セットアップ/構成の手順が非常に最小限であるため、非常に迅速に作業を開始できます。
import React from 'react';
import ReactNotifications from 'react-notifications-component';
import Homepage from './Homepage';
function App() {
return (
<div>
<ReactNotifications />
<Homepage/>
</div>
);
};
内部的にはContextAPI を使用しているため、アプリに1回だけ含める必要があり、どこでも使用できます。 あなたはおそらく配置したいと思うでしょう <ReactNotifications />
アプリのトップレベルの近く。
通知の表示を開始するには、 store
モジュールを任意のコンポーネントに追加し、 store.addNotification()
方法:
import React from 'react';
import { store } from 'react-notifications-component';
import 'react-notifications-component/dist/theme.css';
import 'animate.css';
function Homepage() {
return (
<>
My Website
<button
onClick={() => {
store.addNotification({
title: 'Dropbox',
message: 'Files were synced',
type: 'default', // 'default', 'success', 'info', 'warning'
container: 'bottom-left', // where to position the notifications
animationIn: ["animated", "fadeIn"], // animate.css classes that's applied
animationOut: ["animated", "fadeOut"], // animate.css classes that's applied
dismiss: {
duration: 3000
}
})
}}
>
Add notification
</button>
</>
)
}
ボタンをクリックしてみてください!
注:これを小さなデバイスで表示している場合、全幅の通知が表示される場合があります。
含まれている通知の種類には、成功、警告、情報、デフォルトなどがあります。
通知のカスタマイズ
通知に独自のCSSスタイルが必要な場合は、実際には有効なReact要素を通知として使用できます。
function Homepage() {
return (
<>
My Website
<button
onClick={() => {
store.addNotification({
content: MyNotification,
container: 'bottom-right',
animationIn: ["animated", "fadeIn"],
animationOut: ["animated", "fadeOut"],
dismiss: {
duration: 3000
}
})
}}
>
Add notification
</button>
</>
)
}
function MyNotification() {
return (
<div style={{
display: 'flex',
backgroundColor: '#0f2f26',
borderRadius: 5,
}}>
<AlligatorAvatar/>
<div>
<h4>Alligator.io</h4>
<p>Has joined the chat</p>
</div>
</div>
)
}
注:追加の構成の詳細は、ドキュメントにあります。
まとめ
Reactアプリの通知システムが必要な場合は、必ずreact-notifications-componentを試してください。 デスクトップ/モバイルの互換性、アニメーションオプション、タッチジェスチャ、レスポンシブデザインなど、カバーされなかった機能がたくさんあります。