useToast
Hooks that manage toast notification state, swipe dismissal, auto-timeout, and stacking behavior.
Usage#
import { toast, useToaster } from '@primereact/headless/toaster';
import { useToast } from '@primereact/headless/toast';const toaster = useToaster({ position: 'bottom-right' });
const { rootProps, regionProps, toasts } = toaster;
const { rootProps: toastRootProps, closeProps, state } = useToast({ toast: toastData, toaster });
<div {...rootProps}>
<div {...regionProps}>
{toasts.map((t) => (
<div {...toastRootProps}>
<button {...closeProps}></button>
</div>useToaster manages the toast container; useToast drives per-toast lifecycle. See Primitive for a component-based API.
Features#
- Two-hook architecture ā
useToasterowns container/region state,useToastdrives per-toast lifecycle - Imperative API ā global
toastfunction with severity shortcuts (success,info,warn,error,secondary,contrast) andupdate,dismiss,promisemethods - Swipe-to-dismiss ā directional gesture detection with
data-*lifecycle attributes - Auto-timeout with pause ā timers pause on hover, focus, and when the document is hidden; per-toast
durationoverrides the containertimeout - Stacking and expansion ā stacked layout with expand-on-hover, configurable visible
limit, and positional placement - Grouping ā route toasts to specific containers via matching
groupkeys
Working with toasts#
Creating toasts#
Pass severity directly or use the shortcut method. Each call returns an id you can use later to update or dismiss.
import { toast } from '@primereact/headless/toaster';
const id = toast({ title: 'Update available', description: 'A new version is ready.' });
toast.success({ title: 'Saved' });
toast.error({ title: 'Error', description: 'Something went wrong.' });Promise lifecycle#
toast.promise ties a single toast to a promise ā loading state during the await, then success/error based on the outcome.
toast.promise(fetchData(), {
loading: { title: 'Loadingā¦' },
success: (data) => ({ title: 'Done', description: `Fetched ${data.length} items.` }),
error: (err) => ({ title: 'Failed', description: err.message })
});Updating toasts#
toast.update(id, options) merges new options into an existing toast ā typically used to turn a loading toast into a result.
const id = toast({ loading: true, title: 'Uploadingā¦' });
await upload();
toast.update(id, { loading: false, severity: 'success', title: 'Complete' });Custom JSX#
Pass a React element to render to override the default body. The root wrapper (positioning, animation, swipe) is preserved.
const id = toast({
render: (
<div>
<span>Custom content</span>
<button onClick={() => toast.dismiss(id)}>Close</button>
</div>
)
});Sticky and grouped toasts#
Pass duration: Infinity to keep a toast until dismissed manually. Use group on both the toaster and the call to route toasts to a specific container.
const toaster = useToaster({ group: 'notifications' });
toast({ title: 'Sticky', duration: Infinity, group: 'notifications' });Callbacks#
toast({
title: 'Notification',
onDismiss: (t) => console.log('dismissed', t.id),
onTimeout: (t) => console.log('timed out', t.id)
});Per-toast state#
useToast exposes a state object useful for custom animations or conditional rendering.
const { state } = useToast({ toast: toastData, toaster });
// state.mounted, state.removed, state.swiping, state.swipeOut,
// state.swipeOutDirection, state.isSwiped, state.initialHeightStyling with data attributes#
rootProps from both hooks expose state through data-* attributes.
| Scope | Element | Attributes |
|---|---|---|
toaster | region | data-position, data-expanded |
toast | root | data-mounted, data-removed, data-visible, data-front, data-swiping, data-swipe-out, data-swipe-direction |
[data-position='bottom-right'] {
right: 2rem;
bottom: 2rem;
}
[data-mounted] {
opacity: 1;
}
[data-removed] {
opacity: 0;
}
[data-swiping] {
transition: none;
}
[data-swipe-out][data-swipe-direction='left'] {
transform: translateX(-100%);
}API#
useToaster#
| Name | Type | Default |
|---|---|---|
position | ToasterPosition | 'top-right' |
| Position of the toaster container | ||
mode | ToasterMode | 'stacked' |
| Layout mode of the toaster. | ||
limit | number | 3 |
| Maximum number of toasts to be visible | ||
gap | number | 14 |
| Gap between toasts in pixels | ||
timeout | number | 6000 |
| Timeout for toast auto-dismiss (alias for duration) | ||
group | string | ā |
| Group identifier for toast grouping | ||
useToast#
| Name | Type | Default |
|---|---|---|
toast | ToastType | ā |
| Toast data containing all toast information | ||
toaster | ToasterRootInstance | ā |
| Reference to the parent Toaster instance | ||
Accessibility#
Focus moves into the toast when it contains action buttons, and Escape dismisses when focused. See Primitive for full WAI-ARIA compliance details.