Skip to content

Toast

The Toast component provides non-intrusive notifications that appear temporarily to inform users about the result of an action or system event. It includes a provider component that manages the toast stack and a JavaScript API for triggering toasts programmatically.

Toast notifications are ideal for:

  • Success confirmations (“Changes saved”)
  • Error messages (“Could not connect”)
  • Informational updates (“New message received”)
  • Warnings (“Session expiring soon”)
  • Background process status (“Sync in progress”)

Learn how to implement the Toast component in your project, from basic setup to advanced configurations.

Add the ToastProvider once in your layout (typically near the end of the body):

---
import { ToastProvider } from 'accessible-astro-components'
---
<html>
<body>
<slot />
<ToastProvider />
</body>
</html>

Then trigger toasts anywhere using the global API:

<button id="save-button">Save</button>
<script>
document.getElementById('save-button')?.addEventListener('click', () => {
window.toast?.success('Saved successfully.')
})
</script>

Use the typed helper methods for common toast types:

// Success (green)
window.toast?.success('Changes saved.')
// Error (red)
window.toast?.error('Something went wrong.')
// Info (blue)
window.toast?.info('New updates available.')
// Warning (yellow)
window.toast?.warning('Your session will expire soon.')
// Default (neutral)
window.toast?.show({ message: 'Notification' })

Set duration: 0 to create a toast that doesn’t auto-dismiss:

window.toast?.show({
message: 'Background sync in progress...',
type: 'info',
duration: 0,
})

Override the default duration (in milliseconds) per toast:

window.toast?.success('Quick message', 2000) // 2 seconds
window.toast?.error('Important error', 10000) // 10 seconds
// Dismiss a specific toast by ID
const id = window.toast?.success('Hello')
window.toast?.dismiss(id)
// Dismiss all toasts
window.toast?.dismissAll()

Control where toasts appear using the position prop:

<ToastProvider position="top-center" />

Available positions: bottom-right (default), bottom-left, bottom-center, top-right, top-left, top-center.

Render ToastProvider near the end of your layout body when possible. If the provider must be nested inside an element that creates a stacking context, set portal to move the provider to document.body after initialization:

<ToastProvider portal />

Configure the toast container using these props:

PropTypeDefaultDescription
positionstring'bottom-right'Position in viewport. Options: bottom-right, bottom-left, bottom-center, top-right, top-left, top-center
durationnumber5000Default auto-dismiss time in milliseconds. Set to 0 for persistent toasts
maxToastsnumber5Maximum visible toasts. Oldest are dismissed when exceeded
ariaLabelstring'Notifications'Accessible label for the toast region
zIndexstring | number'var(--z-index-8, 80)'CSS z-index value applied through --toast-z-index
portalbooleanfalseMoves the provider to document.body on initialization to escape ancestor stacking contexts
classstring''Additional CSS classes

Individual toast props (used internally, but useful for understanding the API):

PropTypeDefaultDescription
messagestring'Notification'Toast message content
typestring'default'Visual variant: default, info, success, warning, error
dismissiblebooleantrueWhether to show the dismiss button
dismissLabelstring'Dismiss notification'Accessible label for dismiss button (for i18n)
classstring''Additional CSS classes

The window.toast object provides these methods:

MethodSignatureDescription
show(options: ToastOptions) => stringShow a toast with full options, returns toast ID
success(message: string, duration?: number) => stringShow success toast
error(message: string, duration?: number) => stringShow error toast
info(message: string, duration?: number) => stringShow info toast
warning(message: string, duration?: number) => stringShow warning toast
dismiss(id: string, immediate?: boolean) => voidDismiss specific toast
dismissAll() => voidDismiss all toasts
type ToastOptions = {
message: string
type?: 'info' | 'success' | 'warning' | 'error' | 'default'
duration?: number
dismissible?: boolean
}

The toast system dispatches custom events on document:

// Fired when a toast is shown
document.addEventListener('toast:show', (e) => {
console.log('Toast shown:', e.detail.id, e.detail.type, e.detail.message)
})
// Fired when a toast is dismissed
document.addEventListener('toast:dismiss', (e) => {
console.log('Toast dismissed:', e.detail.id)
})

Accessibility is built into the core of this component:

  • Live region: Uses role="log" for polite screen reader announcements
  • Keyboard support: Press Escape to dismiss all toasts
  • Non-intrusive: Toasts don’t steal focus from the user’s current task
  • Screen reader friendly: Type is announced before the message (e.g., “success: Changes saved”)
  • Reduced motion: Animations respect prefers-reduced-motion
  • Dismiss button: Each toast has an accessible dismiss button

Customize the Toast component while maintaining its accessibility features.

<style is:global>
.toast-provider {
/* Adjust positioning */
--space-l: 2rem;
}
.toast {
/* Custom appearance */
border-radius: 0.75rem;
box-shadow: 0 10px 15px -3px hsl(0 0% 0% / 0.1);
}
.toast.type-success {
--color-success-bg: hsl(142 76% 95%);
--color-success-border: hsl(142 76% 36%);
--color-success-text: hsl(142 76% 20%);
}
.toast.type-error {
--color-error-bg: hsl(0 84% 95%);
--color-error-border: hsl(0 84% 60%);
--color-error-text: hsl(0 84% 20%);
}
.toast-dismiss:focus-visible {
outline-color: currentColor;
outline-offset: 2px;
}
</style>

The toast system uses these CSS custom properties for theming:

/* Spacing and sizing */
--space-xs
--space-2xs
--space-l
--radius-m
/* Type-specific colors (for each type: default, info, success, warning, error) */
--color-{type}-bg
--color-{type}-border
--color-{type}-text
/* Animation */
--toast-translate
--animation-timing
/* Elevation */
--elevation-2
--toast-z-index