Menu

Components

Toast

A brief message that appears in a corner of the screen, tells the user something happened, and goes away by itself.

Introduction

A toast confirms something the user just did, or reports something that happened in the background: “Saved”, “Message sent”, “Connection lost”. It does not block the page, asks for nothing, and disappears on its own.

  • You call a function, toast(), from any place in your code. There is nothing to render where you call it.
  • Screen readers announce each toast. The timer pauses while the pointer is over the toast or it has focus, so nobody loses a message they were reading, and F6 moves the keyboard focus into the stack.
  • Five variants, a description, an action button, a loading state for promises, and up to five toasts shown at once.

A toast must not be the only place a user can learn something important, or hold anything they have to answer. For that, use a dialog or Popover. It is built on the react-aria toast, which is still marked unstable, so its details may change in a future version.

Installation

centerUI has no CLI or registry yet: components are copied into your project. Toast uses Button for its action, so it needs everything Button needs.

# bun
bun add react-aria-components tailwind-variants tailwind-merge clsx

# pnpm
pnpm add react-aria-components tailwind-variants tailwind-merge clsx

# npm
npm install react-aria-components tailwind-variants tailwind-merge clsx

Add Button first (see its Manual installation), then follow the steps below.

Manual installation

Copy these files into your project and keep the paths, or adjust the imports.

1. Add the styles

src/types/toast-styles.tsShow code
import { tv } from "tailwind-variants";

export const toastStyles = tv({
  slots: {
    // The stack of toasts, pinned to a corner or an edge of the screen.
    region:
      "pointer-events-none fixed z-[70] flex max-h-screen w-full max-w-md gap-2 p-4 outline-none",
    toast: [
      "pointer-events-auto relative flex w-full items-start gap-3 rounded-xl border bg-card p-3.5 pr-10 text-card-fg shadow-lg outline-none",
      "animate-toast-in motion-reduce:animate-none",
      "data-focus-visible:ring-2 data-focus-visible:ring-ring",
    ],
    icon: "mt-px flex shrink-0 items-center [&_svg]:size-5",
    content: "flex min-w-0 flex-1 flex-col gap-0.5",
    title: "m-0 text-sm leading-snug font-semibold",
    description: "m-0 text-sm leading-snug text-muted-fg",
    actions: "mt-2 flex items-center gap-2",
    close: [
      "absolute top-2 right-2 flex size-6 cursor-pointer items-center justify-center rounded-md text-muted-fg outline-none transition-colors",
      "data-hovered:bg-muted data-hovered:text-fg",
      "data-focus-visible:ring-2 data-focus-visible:ring-ring",
      "[&_svg]:size-4",
    ],
  },
  variants: {
    variant: {
      default: { icon: "text-muted-fg" },
      success: { icon: "text-success" },
      error: { icon: "text-danger" },
      warning: { icon: "text-warning" },
      info: { icon: "text-primary" },
      loading: {
        icon: "text-muted-fg [&_svg]:animate-spin motion-reduce:[&_svg]:animate-none",
      },
    },
    // Where the stack sits. A stack at the bottom grows upward, so the newest
    // toast, which comes first in the list, is placed at the bottom of it.
    placement: {
      "top-left": {
        region: "top-0 left-0 flex-col [--toast-from:-1rem]",
      },
      "top-center": {
        region: "top-0 left-1/2 -translate-x-1/2 flex-col [--toast-from:-1rem]",
      },
      "top-right": {
        region: "top-0 right-0 flex-col [--toast-from:-1rem]",
      },
      "bottom-left": {
        region: "bottom-0 left-0 flex-col-reverse [--toast-from:1rem]",
      },
      "bottom-center": {
        region:
          "bottom-0 left-1/2 -translate-x-1/2 flex-col-reverse [--toast-from:1rem]",
      },
      "bottom-right": {
        region: "right-0 bottom-0 flex-col-reverse [--toast-from:1rem]",
      },
    },
  },
  defaultVariants: { variant: "default", placement: "bottom-right" },
});

2. Add the Toast file

src/components/ui/toast/toast.tsxShow code
"use client";

import type { ReactNode } from "react";
import {
  Button as AriaButton,
  UNSTABLE_Toast as AriaToast,
  Text,
  UNSTABLE_ToastContent as ToastContent,
  UNSTABLE_ToastQueue as ToastQueue,
  UNSTABLE_ToastRegion as ToastRegion,
} from "react-aria-components";
import {
  AlertTriangleIcon,
  CheckCircleIcon,
  InfoIcon,
  LoaderIcon,
  XCircleIcon,
  XIcon,
} from "@/components/icons";
import { Button } from "@/components/ui/button/button";
import { cn } from "@/lib/cn";
import { toastStyles } from "@/types/toast-styles";

export type ToastVariant =
  | "default"
  | "success"
  | "error"
  | "warning"
  | "info"
  | "loading";

export interface ToastAction {
  label: string;
  /** Runs when the button is pressed. The toast closes after it. */
  onPress?: () => void;
}

export interface ToastOptions {
  /** A second line under the title. */
  description?: ReactNode;
  variant?: ToastVariant;
  /** How long it stays, in milliseconds. `0` keeps it until it is closed. Defaults to 5000. */
  timeout?: number;
  /** A button under the text, such as "Undo". */
  action?: ToastAction;
  /** Runs when the toast closes, whether by the user or after its timeout. */
  onClose?: () => void;
}

interface ToastData {
  title: ReactNode;
  description?: ReactNode;
  variant: ToastVariant;
  action?: ToastAction;
}

const defaultTimeout = 5000;

// The one queue every toast goes through, so `toast()` can be called from
// anywhere: an event handler, a server action's result, another module.
const queue = new ToastQueue<ToastData>({ maxVisibleToasts: 5 });

function show(title: ReactNode, options: ToastOptions = {}) {
  const { timeout = defaultTimeout, onClose, ...content } = options;

  return queue.add(
    { title, variant: "default", ...content },
    // A timeout of 0 means "stay", and the queue takes no timeout to mean that.
    { timeout: timeout > 0 ? timeout : undefined, onClose },
  );
}

type Shortcut = (
  title: ReactNode,
  options?: Omit<ToastOptions, "variant">,
) => string;

const shortcut =
  (variant: ToastVariant): Shortcut =>
  (title, options) =>
    show(title, { ...options, variant });

interface PromiseMessages<T> {
  loading: ReactNode;
  success: ReactNode | ((value: T) => ReactNode);
  error: ReactNode | ((error: unknown) => ReactNode);
}

/**
 * Shows a toast, from anywhere in the app. It returns the key of the toast, to
 * close it later with `toast.dismiss(key)`.
 *
 * @example
 * toast("Saved");
 * toast.success("Profile updated", { description: "Your changes are live." });
 * toast.error("Could not save", { action: { label: "Retry", onPress: save } });
 */
export const toast = Object.assign(show, {
  success: shortcut("success"),
  error: shortcut("error"),
  warning: shortcut("warning"),
  info: shortcut("info"),
  /** Shows a loading toast, then replaces it with the outcome of a promise. */
  promise<T>(promise: Promise<T>, messages: PromiseMessages<T>) {
    const key = show(messages.loading, { variant: "loading", timeout: 0 });
    const resolve = <V,>(
      message: ReactNode | ((value: V) => ReactNode),
      value: V,
    ) =>
      typeof message === "function"
        ? (message as (value: V) => ReactNode)(value)
        : message;

    promise.then(
      (value) => {
        queue.close(key);
        show(resolve(messages.success, value), { variant: "success" });
      },
      (error: unknown) => {
        queue.close(key);
        show(resolve(messages.error, error), { variant: "error" });
      },
    );
    return promise;
  },
  /** Closes one toast, by the key that `toast()` returned. */
  dismiss: (key: string) => queue.close(key),
  /** Closes every toast. */
  clear: () => queue.clear(),
});

const icons: Record<ToastVariant, ReactNode> = {
  default: null,
  success: <CheckCircleIcon />,
  error: <XCircleIcon />,
  warning: <AlertTriangleIcon />,
  info: <InfoIcon />,
  loading: <LoaderIcon />,
};

export interface ToasterProps {
  /** Which corner or edge the toasts stack against. */
  placement?:
    | "top-left"
    | "top-center"
    | "top-right"
    | "bottom-left"
    | "bottom-center"
    | "bottom-right";
  /** Names the region of toasts for screen readers. */
  "aria-label"?: string;
  className?: string;
}

/**
 * Where toasts appear. Put it once in your root layout, and call `toast()`
 * from anywhere. Built on react-aria's toast region, so every toast is
 * announced by screen readers, the timers pause while the pointer is over a
 * toast or it has focus, and F6 moves the keyboard focus into the stack.
 *
 * Use one `Toaster` per app: every toast goes to the same queue.
 *
 * @example
 * // app/layout.tsx
 * <body>
 *   {children}
 *   <Toaster placement="bottom-right" />
 * </body>
 */
export function Toaster({
  placement,
  "aria-label": ariaLabel = "Notifications",
  className,
}: ToasterProps) {
  const styles = toastStyles({ placement });

  return (
    <ToastRegion
      queue={queue}
      aria-label={ariaLabel}
      className={cn(styles.region(), className)}
    >
      {({ toast: queued }) => {
        const { title, description, variant, action } = queued.content;
        const parts = toastStyles({ variant });

        return (
          <AriaToast toast={queued} className={parts.toast()}>
            {icons[variant] ? (
              <span aria-hidden="true" className={parts.icon()}>
                {icons[variant]}
              </span>
            ) : null}
            <ToastContent className={parts.content()}>
              <Text slot="title" className={parts.title()}>
                {title}
              </Text>
              {description ? (
                <Text slot="description" className={parts.description()}>
                  {description}
                </Text>
              ) : null}
              {action ? (
                <div className={parts.actions()}>
                  <Button
                    size="xs"
                    variant="outline"
                    onPress={() => {
                      action.onPress?.();
                      queue.close(queued.key);
                    }}
                  >
                    {action.label}
                  </Button>
                </div>
              ) : null}
            </ToastContent>
            <AriaButton
              slot="close"
              aria-label="Close"
              className={parts.close()}
            >
              <XIcon />
            </AriaButton>
          </AriaToast>
        );
      }}
    </ToastRegion>
  );
}

It imports CheckCircleIcon, XCircleIcon, InfoIcon, AlertTriangleIcon, LoaderIcon and XIcon from @/components/icons. Add those icons, or swap them for your own.

3. Add the slide-in animation

In src/app/globals.css copy the --animate-toast-in line in @theme inline and the toast-in keyframes. Without them toasts still appear, just without sliding in.

4. Use it

import { Toaster, toast } from "@/components/ui/toast/toast";

Setup

Mount the Toaster once in your root layout, then call toast() from anywhere.

// app/layout.tsx: once, for the whole app
import { Toaster } from "@/components/ui/toast/toast";

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Toaster />
      </body>
    </html>
  );
}

// Anywhere else: an event handler, a callback, another module
import { toast } from "@/components/ui/toast/toast";

toast("Changes saved");

Use one Toaster per app: every toast goes into the same queue, so a second one would show each toast twice. This documentation site has one, at the bottom right, and it is the one showing the toasts on this page.

Anatomy

A toast is a card with an icon, text, and optional action, and a close button.

toast.success("Message sent", {
  description: "Ana will get it right away.",
  action: { label: "Undo", onPress: undo },
  timeout: 8000,
});
PartRendered asNotes
Toasterregion, in a portalWhere toasts show: a stack pinned to a corner of the screen. Mount it once.
ToastdivOne notification, with a border, a shadow and a slide-in.
IconsvgSet by the variant: a check, a cross, a warning, an info mark or a spinner. The default has none.
Title / descriptiontextThe message, and an optional second line.
ActionButtonAn optional button under the text, such as Undo.
Close buttonButtonCloses this toast. It is always there.

Examples

Each button shows a toast in the corner of the screen.

Usage

Variants

Use the variant that matches the message. Success and error confirm the outcome of something the user did, warning and info tell them about the state of things.

Description

A second line under the title, for detail that does not fit in it.

Action

A button under the text, such as Undo. Pressing it runs your function and closes the toast. The toast stays until then, or its timeout ends.

Timeout

A toast stays for 5 seconds by default. Give timeout a different time in milliseconds. It pauses while the pointer is over the toast.

Persistent

timeout: 0 keeps the toast until the user closes it or you do, with toast.dismiss and the key that toast() returned. Use it for a state that is still true, such as a lost connection.

Promise

toast.promise shows a loading toast while a promise runs, then swaps it for the outcome. success and error can be a function of the value or the error.

Stacking

At most five toasts show at once, newest nearest the edge of the screen. The others wait, and appear as room is made.

Placement

Placement belongs to the Toaster, so it is the same for every toast in the app.

placementWhere
top-left, top-center, top-rightStacked at the top, newest toast first
bottom-left, bottom-center, bottom-right (default)Stacked at the bottom, newest toast nearest the edge
<Toaster placement="top-center" />
<Toaster placement="bottom-left" />

Component API

The toast function, its options, and the Toaster.

toast

CallWhat it does
toast(title, options?)Shows a toast and returns its key.
toast.success / error / warning / info (title, options?)The same, with that variant.
toast.promise(promise, { loading, success, error })Shows a loading toast, then replaces it with the outcome. Returns the promise.
toast.dismiss(key)Closes one toast, by the key that toast() returned.
toast.clear()Closes every toast.

Options

OptionTypeDefault
descriptionReactNode-
variant"default" | "success" | "error" | "warning" | "info" | "loading""default"
timeoutnumber (ms)5000 (0 keeps it)
action{ label: string; onPress?: () => void }-
onClose() => void-

Toaster

PropTypeDefault
placement"top-left" | "top-center" | "top-right" | "bottom-left" | "bottom-center" | "bottom-right""bottom-right"
aria-labelstring"Notifications"
classNamestring-