import React, { Component } from 'react' import classNames from 'classnames' type Props = Readonly<{ children: (props: any) => any className?: string | null }> type Notify = Readonly<{ id?: string title: string text: string kind: string }> type State = Readonly<{ messages: Notify[] | null }> export default class Notifications extends Component { state = { messages: [], } dismiss = (messageID: string) => { const { messages: currentMessages } = this.state const messages = [...currentMessages] this.setState({ messages: messages.filter(({ id }) => id !== messageID), }) } notify = ({ id = Math.random().toString(16).substr(2), title, text, kind, }: Notify) => { const { messages: currentMessages } = this.state const messages: Notify[] = [...currentMessages] messages.push({ id, title, text, kind }) this.setState({ messages }) setTimeout( ( (messageID) => () => this.dismiss(messageID) )(id), 5000 ) } render() { const { messages } = this.state const { children, className } = this.props return ( <>
{messages.map(({ id, title, text, kind }, i) => (
{title && ( {title} )} {text}
))}
{children(this.notify)} ) } }