import React from 'react'; export default class Notification extends React.PureComponent { constructor() { super(); this.state = { dismissing: false }; this.handleDismiss = this.handleDismiss.bind(this); this.onElement = this.onElement.bind(this); } componentDidMount() { if (this.props.dismissAfter) { this.setDismissTimer(); } } componentWillReceiveProps(next) { // if we have a timer going and the notification text // changed we reset the timer if (next.text !== this.props.text) { if (this.props.dismissAfter) { this.resetDismissTimer(); } if (this.state.dismissing) { this.setState({dismissing: false}); } } } handleDismiss() { this.setState({dismissing: true}); } onElement(el) { if (el) { el.addEventListener('webkitTransitionEnd', () => { if (this.state.dismissing) { this.props.onDismiss(); } }); const {backgroundColor} = this.props; if (backgroundColor) { el.style.setProperty('background-color', backgroundColor, 'important'); } } } setDismissTimer() { this.dismissTimer = setTimeout(() => { this.handleDismiss(); }, this.props.dismissAfter); } resetDismissTimer() { clearTimeout(this.dismissTimer); this.setDismissTimer(); } componentWillUnmount() { clearTimeout(this.dismissTimer); } render() { const {backgroundColor} = this.props; const opacity = this.state.dismissing ? 0 : 1; return (
{this.props.customChildrenBefore} {this.props.children || this.props.text} {this.props.userDismissable ? ( [x] ) : null} {this.props.customChildren}
); } }