Skip to content

Instantly share code, notes, and snippets.

@danielsmykowski1
Last active November 25, 2019 20:26
Show Gist options
  • Save danielsmykowski1/f6397680ebf30f96ed254327d3953429 to your computer and use it in GitHub Desktop.
Save danielsmykowski1/f6397680ebf30f96ed254327d3953429 to your computer and use it in GitHub Desktop.
A React Typescript Notifications component
import * as React from 'react'
import * as NotificationSystem from 'react-notification-system'
import { Message } from 'semantic-ui-react'
import { AsyncError } from '../../models/async.models'
import { I18N } from '../../i18n';
export interface NotificationConfig {
position?: 'tr' | 'tl' | 'tc' | 'br' | 'bl' | 'bc'
delay?: number
dismissible?: boolean
onDismiss?: Function
}
export interface Notification extends NotificationConfig {
title?: string
message?: string
level?: 'error' | 'warning' | 'info' | 'success'
}
export class Notifications extends React.Component {
protected notifications: NotificationSystem.System
add(notification: Notification): number {
const config = {
position: notification.position || 'tr',
autoDismiss: notification.delay
? notification.delay / 1000
: (notification.title + notification.message).length * .13,
dismissible: notification.dismissible || true,
}
const uid = this.notifications.addNotification({
level: notification.level,
...config,
onRemove: (notif) => {
if (notification.onDismiss && notif.uid === uid)
notification.onDismiss()
},
children: [
<Message
key='notification'
negative={notification.level === 'error'}
warning={notification.level === 'warning'}
info={notification.level === 'info'}
positive={notification.level === 'success'}
icon={notification.level === 'error' ||
notification.level === 'warning' ?
'warning circle' : 'info circle'}
header={notification.title}
content={notification.message}
onDismiss={config.dismissible ? () => null : null}
/>,
],
}).uid as number
return uid
}
addFromAsyncError(error: AsyncError, config?: NotificationConfig): number {
const i18n = I18N.asyncError(error)
return this.add({
level: error.sevirity === 'ERROR' ? 'error' : 'warning',
title: i18n.text,
message: i18n.desc,
...config || {},
})
}
render() {
return (
<NotificationSystem
ref={ref => this.notifications = ref}
style={{
Containers: {
DefaultStyle: {
width: 380,
},
},
NotificationItem: {
DefaultStyle: {
padding: '0px',
borderTop: '',
backgroundColor: '',
boxShadow: '',
},
},
}}
/>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment