-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
70 lines (55 loc) · 1.48 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import React, {Component} from 'react';
export default class Notify extends Component {
constructor() {
super();
this.wasMounted = true;
this.key = 0;
this.state = {};
}
componentWillUnmount() {
this.wasMounted = false;
}
success(title, msg, time) {
this.addNotify(title, msg, time, 'success');
}
error(title, msg, time) {
this.addNotify(title, msg, time, 'error');
}
info(title, msg, time) {
this.addNotify(title, msg, time, 'info');
}
addNotify(title, msg, time, theme) {
const key = this.key++;
const state = Object.assign(this.state, { [key]: { title, msg, time, theme } });
this.setState(state, () => this.countToHide(time, key));
}
countToHide(duration, key) {
setTimeout(() => {
this.hideNotification(key);
}, duration);
}
hideNotification(key) {
if( !this.wasMounted ) {
return;
}
this.setState((state) => {
delete state[key];
return state;
});
}
item(key) {
const { theme, title, msg } = this.state[key];
return (
<div key={key} className={`notify-item ${theme}`} onClick={() => this.hideNotification(key)}>
<p className="notify-title">{title}</p>
<p className="notify-body">{msg}</p>
</div>
);
}
render() {
const { state } = this;
const keys = Object.keys(state);
const el = keys.map((key) => this.item(key));
return <div className="notify-container">{el}</div>;
}
}