Skip to content

Instantly share code, notes, and snippets.

@fbedussi
Created February 19, 2022 14:58
Show Gist options
  • Save fbedussi/3a8215cdc5ff6e1ea94cc1ca35910277 to your computer and use it in GitHub Desktop.
Save fbedussi/3a8215cdc5ff6e1ea94cc1ca35910277 to your computer and use it in GitHub Desktop.
toasts.tsx
import * as React from 'react'
import { render } from 'react-dom'
import { ThemeProvider } from 'styled-components'
import Toast, { ToastVariant } from '@components/Toast/Toast'
import { SerializedError } from '@reduxjs/toolkit'
import { FetchBaseQueryError } from '@reduxjs/toolkit/dist/query'
import { theme } from '@root/theme'
import CallErrorAlert from '../components/CallErrorAlert/CallErrorAlert'
let containerDomNode = document.querySelector('#fa-toast-container')
export const showToast = ({ variant, closable, content }: { closable?: boolean, variant?: ToastVariant, content: React.ReactNode }) => {
if (!containerDomNode) {
containerDomNode = document.createElement('div')
containerDomNode.id = 'fa-toast-container'
document.body.appendChild(containerDomNode);
}
render(<ThemeProvider theme={theme}><Toast variant={variant} closable={closable}>{content}</Toast></ThemeProvider>, containerDomNode);
}
export const showErrorToast = ({ error, origin }: { error: FetchBaseQueryError | SerializedError, origin: string }) => {
showToast({ variant: 'error', closable: true, content: <CallErrorAlert error={error} origin={origin} /> })
}
export const removeToast = () => {
const toast = containerDomNode?.querySelector('div')
if (toast) {
const style = window.getComputedStyle(toast, null).getPropertyValue("transition");
const hasTransition = style !== "all 0s ease 0s"
if (hasTransition) {
toast.addEventListener('transitionend', () => {
if (containerDomNode) {
containerDomNode.innerHTML = ''
}
})
toast.classList.add('animation-out')
} else {
if (containerDomNode) {
containerDomNode.innerHTML = ''
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment