Skip to Content
Neshel-UI
Components

Toast

Short, non-blocking notifications from a store you create once; announced to screen readers once.

Client component ("use client")

Not in 0.1.0 yet

This API is on the main branch but not in the 0.1.0 packages on npm. To use it today, install locally packed tarballs.

Purpose

A toast confirms the result of an action ("Draft saved") or reports a problem without interrupting the user. createToaster() returns a store that holds the toasts, their timers and the queue; <Toaster> renders it. No provider is needed.

Import

import.tsx
import { createToaster, Toaster } from "@neshel-ui/components";

Usage

Preview: toast-basic
Preview theme
    toast-basic.tsx
    "use client";
    import { Button, createToaster, Toaster } from "@neshel-ui/components";
    
    // One store for the application; no provider. Create it once (module scope or a memo).
    const toaster = createToaster({ max: 3 });
    
    export default function ToastBasic() {
      return (
        <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
          <Button variant="outline" onClick={() => toaster.show({ title: "Draft saved" })}>
            Neutral
          </Button>
          <Button
            variant="outline"
            onClick={() => toaster.show({ title: "Payment received", tone: "success" })}
          >
            Success
          </Button>
          <Button
            variant="outline"
            onClick={() => toaster.show({ title: "Upload failed", tone: "error" })}
          >
            Error
          </Button>
          <Button
            variant="outline"
            onClick={() =>
              toaster.show({
                title: "Message archived",
                action: { label: "Undo", onAction: () => toaster.show({ title: "Restored" }) },
              })
            }
          >
            With action
          </Button>
          <Toaster toaster={toaster} />
        </div>
      );
    }

    API

    ToasterOptions

    ToasterOptions
    PropTypeDefaultDescription
    maxnumber—Visible toasts at most (1–10, default 3).
    overflow"evict" | "queue"—What happens beyond max: "evict" (default) dismisses the oldest unprotected toast; "queue" keeps the new toast waiting (no timer, not rendered, not announced) until a visible one is dismissed.

    ToastInput

    ToastInput
    PropTypeDefaultDescription
    actionToastAction—One optional action; it makes the toast persistent unless duration is given.
    descriptionstring——
    durationnumber—ms (clamped to 1000–60000), Infinity (persistent), or omitted for the automatic duration.
    idstring—Stable id (default generated). Showing an existing id replaces its content and restarts its timer.
    title(required)string——
    toneToastTone"neutral"Default "neutral". "error" is announced assertively.

    ToasterProps

    ToasterProps
    PropTypeDefaultDescription
    closeLabelstring"Close"Accessible name of each close button (default "Close").
    hotkeystring | null—Key that moves focus to the toasts (default "F8"; null disables).
    labelstring"Notifications"Accessible name of the notifications region (default "Notifications").
    motion"css" | "none"—"css" (default): Components' enter/exit transitions. "none": no package motion (e.g. Animations F06).
    placementToasterPlacement—Viewport corner (logical; default "bottom-end").
    refRef<HTMLElement>——
    toaster(required)ToasterStore—The store from createToaster(). The consumer owns it; <Toaster> never destroys it.

    Also accepts the props of: React DOM attributes.

    ToasterStore

    ToasterStore
    PropTypeDefaultDescription
    destroy(required)() => void—Clears every toast, timer, pause reason and listener (idempotent); subscribers are notified once of the final, empty state. A destroyed store is inert: show() still validates its input but returns "" and creates nothing, subscribe() registers nothing, the rest do nothing.
    dismiss(required)(id: string) => void——
    dismissAll(required)() => void——
    pause(required)(reason?: string) => void"manual"Pause every timer for reason (default "manual").
    paused(required)boolean—Whether any pause reason is active.
    protect(required)(id: string | undefined) => void—A toast that must not be evicted by overflow (the focused one), or undefined.
    queued(required)readonly Toast[]—Toasts waiting for a free slot (overflow: "queue"), oldest first.
    resume(required)(reason?: string) => void——
    show(required)(input: ToastInput) => string—Shows (or replaces) a toast; returns its id ("" once destroyed). Invalid input throws.
    subscribe(required)(listener: () => void) => () => void——
    toasts(required)readonly Toast[]—Visible toasts, oldest first.

    Toast is the stored record (with version), ToastAction the optional action, ToastTone is "neutral" | "success" | "warning" | "error" and ToasterPlacement the four logical corners.

    Behaviour

    • Automatic duration: 6 s plus 60 ms per character (at most 20 s); toasts with an action stay until closed unless duration is given; Infinity makes any toast persistent.
    • Timers pause while a toast is hovered or focused and while the page is hidden.
    • More than max toasts: the oldest unfocused one is dismissed, or with overflow: "queue" new toasts wait for a free slot.
    • destroy() clears everything and is idempotent; a destroyed store ignores later calls.
    • Showing an existing id again replaces its content and restarts its timer — "Uploading…" becomes "Uploaded" in the same toast.
    • pause(reason) and resume(reason) add your own reasons; timers run only when none is active and continue with the remaining time.
    • Several <Toaster>s may render one store; each toast is announced once.
    • motion="none" turns off the built-in transitions, e.g. to let @neshel-ui/animations F06 animate the toasts.
    Preview: toast-queue
    Preview theme
      toast-queue.tsx
      "use client";
      import { Button, createToaster, Toaster } from "@neshel-ui/components";
      
      const toaster = createToaster({ max: 2, overflow: "queue" });
      
      function upload() {
        // The same id: the second call replaces the content of the first toast.
        toaster.show({ id: "upload", title: "Uploading…", duration: Number.POSITIVE_INFINITY });
        setTimeout(() => toaster.show({ id: "upload", title: "Uploaded", tone: "success" }), 1500);
      }
      
      export default function ToastQueue() {
        return (
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            <Button variant="outline" onClick={upload}>
              Update one toast
            </Button>
            <Button
              variant="outline"
              onClick={() => {
                for (const name of ["One", "Two", "Three"]) toaster.show({ title: `File ${name}` });
              }}
            >
              Queue three
            </Button>
            <Toaster toaster={toaster} placement="bottom-start" label="Uploads" hotkey="F7" />
          </div>
        );
      }

      Placement and lifetime

      Create the store once per application (module scope) and render one <Toaster> near the root. With a store created inside a component, call destroy() when it unmounts; <Toaster> never destroys it. On a server, do not share one module store between requests: show toasts only from the browser. placement uses logical corners, so bottom-end is at the left in right-to-left pages.

      Accessibility

      • Two live regions exist before any toast: polite (role="status") and, for tone: "error", assertive (role="alert"). Each toast is announced once.
      • A toast appearing never moves focus. The hotkey (F8 by default) moves focus to the toasts; Escape closes the focused toast and focus moves to the next toast or back to where it came from.
      • Every toast has a labelled close button (closeLabel).

      Keyboard

      KeyAction
      F8Move focus to the toasts (hotkey)
      EscapeClose the focused toast
      TabMove between toast buttons

      Styling and motion

      motion="css" uses the built-in transitions (opacity only under reduced motion). With motion="none", another layer can animate the items: each one exposes data-state (entering, open, closing) and dispatches a neshel-exit event whose detail.waitUntil(promise) keeps it mounted for at most one second.

      Limitations

      No provider, no global singleton, no swipe to dismiss and no promise helper.

      Common mistakes

      • Essential information or a required decision in a toast: use an inline message or an AlertDialog.
      • Adding your own live region for the same message: it would be announced twice.
      • An action that exists only in the toast: offer it elsewhere too.
      Edit on GitHub

      On this page