Toast Notifications
Build a toast notification system that any component can trigger.
<ToastProvider duration={5000} max={3}>
<App />
</ToastProvider>
// anywhere inside:
const toast = useToast();
toast.show({ type: 'success', message: 'Changes saved.' });
Requirements
-
ToastProviderrenders a toast stack in the bottom-right corner and exposesshow({ type, message })through context.typeissuccess,errororinfo, each with its own colour and icon. -
Each toast has a Dismiss button. Its accessible name is "Dismiss notification".
-
Auto-dismiss after
durationms (default 5000). The timer pauses while the toast is hovered or has keyboard focus and resumes with the time that was left. -
At most
maxtoasts (default 3) are visible. Showing another one drops the oldest. -
Announcements:
- success and info are announced politely (
role="status") - errors are announced assertively (
role="alert").
The live-region containers must exist before any toast is added.
- success and info are announced politely (
-
Toasts don't steal focus.
-
Demo: three buttons ("Show success", "Show error", "Show info").
Appaccepts atoastDurationprop that it passes to the provider.
Follow-up
- Why does
useToastreturn a stable object, and why does that matter? - Is an auto-dismissing error message acceptable? What do the WCAG timing rules say?
- How would you trigger toasts from outside React (an axios interceptor)?
Spotted a mistake or a rights concern? Report an issue