AI
NUI logov3.1.0

Toast & ToastProvider

An accessible, animated toast notification system built for React and Next.js applications. Supports semantic visual variants, stacked layouts, auto-dismiss with pause-on-hover, SSR-friendly portals, and dual dispatch APIs: hook-based (useToast) and zero-JSX imperative notifications (nui.toast, nui.success, nui.error).

tsx
import { ToastProvider, useToast, nui } from '@nofinite/nui';

Interactive Preview


Setup

Mount <ToastProvider> once at the root of your application (e.g. inside app/layout.tsx):

tsx
// app/layout.tsx (Next.js App Router)
import { ToastProvider } from '@nofinite/nui';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <ToastProvider>
          {children}
        </ToastProvider>
      </body>
    </html>
  );
}

Dual Usage Patterns

NUI provides two complementary ways to trigger notifications:

1. Hook-Based (useToast)

Use inside any React component within the <ToastProvider> tree:

tsx
'use client';
import { Button, useToast } from '@nofinite/nui';

export function SaveButton() {
  const toast = useToast();

  const handleSave = () => {
    toast.show('Settings saved successfully', {
      variant: 'success',
      description: 'Your changes have been synced across all devices.',
      duration: 5000,
    });
  };

  return (
    <Button variant="primary" onClick={handleSave}>
      Save Changes
    </Button>
  );
}

2. Zero-JSX Imperative (nui.*)

Trigger toasts directly from event handlers, API interceptors, or utility functions without needing React hooks or component context:

tsx
import { nui } from '@nofinite/nui';

// In an API response handler or client utility:
async function updateProfile(data) {
  try {
    await api.post('/profile', data);
    nui.success('Profile updated successfully!');
  } catch (err) {
    nui.error('Failed to update profile. Please try again.');
  }
}

Semantic Variants

Toasts use semantic design tokens for instant visual hierarchy:

VariantToken AccentTypical Use Case
defaultvar(--color-primary)General system updates, feature tips, neutral notifications
successvar(--color-success)Confirmed operations, completed exports, successful saves
errorvar(--color-danger)Network errors, validation failures, failed operations
warningvar(--color-warning)Rate limit warnings, session expiration alerts, unsaved work
tsx
// Variant examples
toast.show('Database backup created', { variant: 'success' });
toast.show('Network disconnected', { variant: 'error' });
toast.show('Storage limit at 92%', { variant: 'warning' });
toast.show('New comment received', { variant: 'default' });

Manual Dismissal

toast.show() returns a unique string id. You can programmatically dismiss a toast before its duration expires:

tsx
const toastId = toast.show('Uploading file...', { duration: 15000 });

// Later when upload finishes:
toast.dismiss(toastId);
toast.show('Upload complete!', { variant: 'success' });

Toast Options Reference

The show() function and programmatic helpers accept the following options:

OptionTypeDefaultDescription
variant'default' | 'success' | 'error' | 'warning''default'Semantic color variant of the notification
descriptionReact.ReactNodeundefinedSecondary supporting text below the main message
durationnumber4000Auto-dismiss time in milliseconds (set to Infinity to keep persistent)

Accessibility & Animations

  • Screen Readers: Container declares aria-live="polite" and each individual notification applies role="status".
  • Keyboard Navigation: Includes an accessible close button with aria-label="Close notification".
  • Hover to Pause: Hovering over an active toast pauses its auto-dismiss countdown timer so users have sufficient time to read long messages.
  • Motion Safety: Automatically honors prefers-reduced-motion media queries, replacing sliding transitions with instant opacity fades.

Best Practices

Do

  • Mount <ToastProvider> once at the application root layout.
  • Pair toasts with clear, actionable text.
  • Use description for helpful context (e.g. error reasons or next steps).
  • Rely on pause-on-hover for notifications with dense messages.

Don't

  • Do not fire multiple identical toasts in rapid succession; consolidate notifications.
  • Avoid using toasts for critical confirm/reject interactions; use <DialogProvider> with nui.confirm() instead.
  • Do not hardcode fixed hex colors in toast bodies; let NUI semantic tokens adapt automatically across light and dark modes.

API Reference

ToastProvider PropsHTML Attributes

Inherits all standard attributes and event handlers from { children: React.ReactNode } — Mount once at app root to enable toast context (useToast) and imperative toast bridging (nui.toast). Supports className for semantic NUICSS superclasses and ref forwarding.