Hook
Invoke useToasts
hook in a functional component to extract helpers to create, modify, view and remove toasts.
import { useToasts } from 'react-cooked-bread'
const Component = () => {
const { addToast, removeToast, removeAllToasts, updateToast, toasts } = useToasts()
useEffect(() => {
if (error) {
addToast(error.message, {
type: 'error',
})
}
}, [error, addToast])
// ...
}
Occasionally, you may need to use a higher-order component instead to access the ToastContextProps
.
Props
Prop descriptions
Property | Type | Description |
---|---|---|
addToast | Function | Create a toast and add it to the queue, returns the toast id |
removeToast | Function | Remove a specific toast by id |
removeAllToasts | Function | Remove all toasts |
updateToast | Function | Update a specific toast by id |
toasts | Array | A list of active toast properties |
Add Toast
Create a new toast
Usage
const newToastId: string = addToast(content: ReactNode, {
type: 'success',
autoDismiss: true,
onDismiss: () => {
console.log('bye!')
}
})
TypeScript
type AddToast = (content: ReactNode, options: AddToastOptions) => string
type AddToastOptions = {
id?: Id
type?: ToastTypeOption
autoDismiss?: boolean
timeout?: number
transitionDuration?: TransitionDuration
title?: string
subtitle?: string
onDismiss?: (id: Id | undefined) => void
}
Remove Toast
Remove a toast by its ID
Usage
removeToast(id)
TypeScript
type RemoveToast = (id: string) => void
Remove All Toasts
Removes all active toasts
Usage
removeAllToasts()
TypeScript
type RemoveAllToasts = () => void
Update Toast
This helper function works like a patch update. Updated fields are merged with the existing options.
Usage
updateToast(id, {
autoDismiss: false,
})
TypeScript
type UpdateToast = (id: string, options: UpdateToastOptions) => void
interface UpdateToastOptions extends AddToastOptions {
content?: ReactNode
}
Toasts
A collection of active toasts
Example
<>
{toasts.map(({ id, content, type, autoDismiss }) => (
<div key={id} className={`${type}-toast`}>
{content}
{autoDismiss && <Timer />}
</div>
))}
</>
TypeScript
type ActiveToast = {
id: string
content: ReactNode
type: ToastTypeOption
autoDismiss?: boolean
timeout?: number
transitionDuration?: TransitionDuration
onDismiss?: (id: string | undefined) => void
title?: string
subtitle?: string
}