File size: 2,721 Bytes
181e22f | 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import classnames from 'classnames';
import uuidv4 from 'uuid/v4';
import { TransitionGroup, CSSTransition } from 'react-transition-group';
import PropTypes from 'prop-types';
import Icon from './Icon';
import styles from './Toast.cm.styl';
const TOAST_TYPES = {
SUCCESS: 1,
ERROR: 2,
INFO: 3,
};
class Toast extends Component {
constructor(props) {
super(props);
this.state = {
toasts: [],
};
}
add(type, title) {
const newId = uuidv4();
const toast = {
id: newId,
type,
title,
};
setTimeout(() => {
this.setState(state => {
const nextToasts = state.toasts.filter(t => t.id !== newId);
return {
toasts: nextToasts,
};
});
}, 2000);
this.setState(state => {
return {
toasts: [...state.toasts, toast],
};
});
}
render() {
const {
toasts = [],
} = this.state;
const iconNames = {
[TOAST_TYPES.SUCCESS]: 'check',
[TOAST_TYPES.ERROR]: 'close',
[TOAST_TYPES.INFO]: 'info',
};
const classNamesOfToastType = {
[TOAST_TYPES.SUCCESS]: styles.success,
[TOAST_TYPES.ERROR]: styles.error,
[TOAST_TYPES.INFO]: styles.info,
};
return (
<div className={styles.container}>
<TransitionGroup component={null}>
{toasts.map(t => {
const toastType = t.type;
return (
<CSSTransition
key={t.id}
classNames="toast-animation"
timeout={220}
>
<div className={classnames(styles.toast, classNamesOfToastType[toastType])}>
<div className={classnames(styles.iconWrapper, classNamesOfToastType[toastType])}>
<Icon name={iconNames[toastType]} />
</div>
<div key={t.id} className={classnames(styles.content, classNamesOfToastType[toastType])}>
{t.title}
</div>
</div>
</CSSTransition>
);
})}
</TransitionGroup>
</div>
);
}
}
const div = document.createElement('div');
document.body.appendChild(div);
const toastInstance = React.createRef();
ReactDOM.render(<Toast ref={toastInstance} />, div);
Toast.success = (title) => {
toastInstance.current.add(TOAST_TYPES.SUCCESS, title);
};
Toast.error = (title) => {
toastInstance.current.add(TOAST_TYPES.ERROR, title);
};
Toast.info = (title) => {
toastInstance.current.add(TOAST_TYPES.INFO, title);
};
Toast.propTypes = {
toasts: PropTypes.array,
};
export default Toast;
|