Toast

A short notice that goes away on its own.

Put one Toaster near the app’s root, then call toast() from anywhere when something finishes. A toast can offer an action, like Undo. Toasts stack, fan out when you hover or focus them, and can be swiped away. Screen readers announce them without moving focus.

Preview
basic.tsx
import { useState } from "react"

import { Button } from "~/components/ui/button"
import { createToaster, Toaster } from "~/components/ui/toast"

export default function Example() {
  // A queue of its own, so this example's toasts don't mix with any others.
  const [toast] = useState(() => createToaster())
  const [chapter, setChapter] = useState(12)
  return (
    <>
      <Button
        onClick={() => {
          toast(`Chapter ${chapter} saved`, {
            description: `${(chapter * 351).toLocaleString("en-US")} words`,
            action: { label: "Undo", onAction: () => {} },
          })
          setChapter(chapter + 1)
        }}
      >
        Save chapter
      </Button>
      <Toaster toaster={toast} />
    </>
  )
}

Dependencies

What it's built from and what's built from it in Base, read from the imports in its source.

UsesButtonprimitiveTextprimitive
Used byNothing yet.
Packages @ui-sdk/core@0.1.0-beta.20@ui-sdk/react@0.1.0-beta.20lucide-react@1.73.0

Installation

Set the project up for Base once first, as Getting started shows. Then add it with the CLI, or by hand.

With the CLI

terminal
npx shadcn@latest add https://design.zepez.dev/r/base/toast.json

Manually

Install its packages:

terminal
npm install @ui-sdk/core@0.1.0-beta.20 @ui-sdk/react@0.1.0-beta.20 lucide-react@1.73.0

Add the components it uses first, listed under Dependencies.

Then copy the source:

components/ui/toast.tsx
import {
  createToaster,
  Toast as ToastPrimitive,
  ToastAction as ToastActionPrimitive,
  ToastClose as ToastClosePrimitive,
  ToastDescription as ToastDescriptionPrimitive,
  ToastRegion as ToastRegionPrimitive,
  ToastTitle as ToastTitlePrimitive,
  toast,
} from "@ui-sdk/react/toast"
import { X } from "lucide-react"
import type * as React from "react"

import { buttonVariants } from "~/components/ui/button"
import { textVariants } from "~/components/ui/text"
import { cnState } from "~/lib/utils"

/*
 * Short notices that go away on their own. Put a `Toaster` near the app's root
 * once, then call `toast("Saved", { description: "…" })` from anywhere.
 */

/** A toast's card: a stack that peeks behind the newest toast and fans out on hover or focus. */
function Toast({ className, ...props }: React.ComponentProps<typeof ToastPrimitive>) {
  return (
    <ToastPrimitive
      className={cnState(
        [
          textVariants({ size: "sm" }),
          "absolute inset-x-0 flex h-(--toast-height) items-center gap-md overflow-hidden rounded-lg bg-overlay p-lg text-overlay-foreground shadow-lg ring-1 ring-foreground/5 select-none dark:ring-foreground/10",
          "z-[calc(100-var(--toast-index))] group-data-[side=bottom]/toasts:bottom-0 group-data-[side=top]/toasts:top-0",
          // --y places the toast: behind the newest it peeks out by its index; expanded, it
          // clears the toasts in front of it. Swipes add to it, and are 0 when not swiping.
          "group-data-[side=bottom]/toasts:[--y:calc(var(--toast-index)*-0.75rem)] group-data-[side=top]/toasts:[--y:calc(var(--toast-index)*0.75rem)]",
          "data-expanded:group-data-[side=bottom]/toasts:[--y:calc(-1*(var(--toast-offset)+var(--toast-index)*0.75rem))] data-expanded:group-data-[side=top]/toasts:[--y:calc(var(--toast-offset)+var(--toast-index)*0.75rem)]",
          "translate-x-[var(--toast-swipe-x,0px)] translate-y-[calc(var(--y)+var(--toast-swipe-y,0px))] scale-[calc(1-var(--toast-index)*0.05)] data-expanded:scale-100",
          // Collapsed, the toasts behind the newest show only as tall as it is.
          "not-data-front:not-data-expanded:h-(--toast-front-height)",
          "transition-[translate,scale,opacity,height] duration-400 ease-[cubic-bezier(0.21,1.02,0.73,1)] data-starting-style:transition-none data-swiping:transition-none motion-reduce:transition-opacity",
          // Entering: the newest slides in from the edge; the others fade in.
          "data-starting-style:data-front:group-data-[side=bottom]/toasts:[--y:100%] data-starting-style:data-front:group-data-[side=top]/toasts:[--y:-100%] data-starting-style:not-data-front:opacity-0",
          // Leaving: fade, or slide off the way it was swiped.
          "data-ending-style:opacity-0 data-ending-style:data-[swipe-direction=right]:translate-x-full data-ending-style:data-[swipe-direction=left]:-translate-x-full data-ending-style:data-[swipe-direction=down]:[--y:100%] data-ending-style:data-[swipe-direction=up]:[--y:-100%]",
        ].join(" "),
        className,
      )}
      {...props}
    />
  )
}

/** The toast's message. Empty, it shows the text passed to `toast()`. */
function ToastTitle({ className, ...props }: React.ComponentProps<typeof ToastTitlePrimitive>) {
  return (
    <ToastTitlePrimitive
      className={cnState(textVariants({ weight: "medium" }), className)}
      {...props}
    />
  )
}

/** More detail, under the title. Empty, it shows the toast's `description`. */
function ToastDescription({
  className,
  ...props
}: React.ComponentProps<typeof ToastDescriptionPrimitive>) {
  return (
    <ToastDescriptionPrimitive
      className={cnState(textVariants({ tone: "muted" }), className)}
      {...props}
    />
  )
}

/** A button for the toast's `action`, like Undo. Empty, it shows the action's label. */
function ToastAction({ className, ...props }: React.ComponentProps<typeof ToastActionPrimitive>) {
  return (
    <ToastActionPrimitive
      className={cnState(buttonVariants({ variant: "outline", size: "sm" }), className)}
      {...props}
    />
  )
}

/** Dismisses the toast. */
function ToastClose({
  className,
  children,
  ...props
}: React.ComponentProps<typeof ToastClosePrimitive>) {
  return (
    <ToastClosePrimitive
      aria-label="Dismiss"
      className={cnState(buttonVariants({ variant: "ghost", size: "icon-xs" }), className)}
      {...props}
    >
      {children ?? <X className="size-3.5" />}
    </ToastClosePrimitive>
  )
}

type ToasterProps = Omit<React.ComponentProps<typeof ToastRegionPrimitive>, "children">

/**
 * Where toasts appear: the bottom right unless `side` and `align` say otherwise.
 * Put one near the app's root. Pass `toaster` for a queue of its own, from `createToaster()`.
 */
function Toaster({ className, side = "bottom", align = "end", ...props }: ToasterProps) {
  return (
    <ToastRegionPrimitive
      side={side}
      align={align}
      className={cnState(
        [
          "group/toasts fixed z-50 h-(--toast-front-height) w-89 max-w-[calc(100vw-2rem)] transition-[height] duration-300",
          "data-expanded:h-[calc(var(--toast-stack-height)+(var(--toast-count)-1)*0.75rem)]",
          "data-[side=bottom]:bottom-lg data-[side=top]:top-lg",
          "data-[align=end]:right-lg data-[align=start]:left-lg data-[align=center]:left-1/2 data-[align=center]:-translate-x-1/2",
        ].join(" "),
        className,
      )}
      {...props}
    >
      {() => (
        <Toast>
          <div className="grid min-w-0 flex-1 gap-3xs">
            <ToastTitle />
            <ToastDescription />
          </div>
          <ToastAction />
          <ToastClose />
        </Toast>
      )}
    </ToastRegionPrimitive>
  )
}

export {
  createToaster,
  Toast,
  ToastAction,
  ToastClose,
  ToastDescription,
  Toaster,
  ToastTitle,
  toast,
}
export type { ToasterProps }

API reference

Generated from Base's types. Props marked ours are added here; the rest come from the ui-sdk part it wraps. Every part also accepts its element's native attributes.

Toast

A toast's card: a stack that peeks behind the newest toast and fans out on hover or focus.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: ToastState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: ToastState) => string)

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<ToastState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: ToastState) => CSSProperties)

ToastAction

A button for the toast's action, like Undo. Empty, it shows the action's label.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: ToastButtonState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: ToastButtonState) => string)

disabled

Stops presses. The button is natively disabled, so it leaves the tab order and its form doesn't submit through it, unless focusableWhenDisabled is set.

Type boolean · Default false

dismiss

Whether pressing it dismisses the toast.

Type boolean · Default the toast's `action.dismiss`, else true

onAction

Runs when it's pressed, instead of the toast's own action.onAction. A returned Promise marks it pending. details.source says how it was pressed, for changes made after an await.

Type (event: Event, details: ActionDetails) => unknown

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<ToastButtonState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: ToastButtonState) => CSSProperties)

ToastClose

Dismisses the toast.

action

Runs before the toast closes. A returned Promise keeps it open and the button pending until it settles. details.source says how it was pressed, for changes made after an await.

Type (event: Event, details: ActionDetails) => unknown

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: ToastButtonState) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: ToastButtonState) => string)

disabled

Stops presses. The button is natively disabled, so it leaves the tab order and its form doesn't submit through it, unless focusableWhenDisabled is set.

Type boolean · Default false

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<ToastButtonState>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: ToastButtonState) => CSSProperties)

ToastDescription

More detail, under the title. Empty, it shows the toast's description.

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: {}) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: {}) => string)

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<{}>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: {}) => CSSProperties)

Toaster

Where toasts appear: the bottom right unless side and align say otherwise. Put one near the app's root. Pass toaster for a queue of its own, from createToaster().

align

Where along that edge. "start" and "end" follow the writing direction, and swiping toward them dismisses too.

Type "center" | "start" | "end" · Default end

className

Class names, or a function of the part's state that returns them.

Type string | ((state: ToastRegionState) => string)

container

Where the region renders. Without top layer support, the body.

Type PopupContainer

debug

Logs every state change with its reason to the console, in development builds.

Type boolean

expanded

Whether the stack is always expanded. Otherwise it expands while the pointer or focus is in it.

Type boolean · Default false

maxVisible

How many toasts show at once. Older ones wait, with their timers stopped, until there's room.

Type number · Default 3

pendingAnnouncement

What screen readers hear once a toast's action or close button has been pending for a second, so a slow action doesn't pass in silence. Set it in the page's language. An empty string says nothing.

Type string · Default "Loading"

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<ToastRegionState>

shortcut

The key that moves focus into the region and back, like "F6" or "alt+t". null turns it off.

Type string | null · Default "F6"

side

The edge of the viewport it sits on. Swiping toward it dismisses a toast.

Type "top" | "bottom" · Default bottom

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: ToastRegionState) => CSSProperties)

toaster

The queue it shows. A second toaster, from createToaster(), gives a second region its own toasts.

Type Toaster<any> · Default the shared `toast`

ToastTitle

The toast's message. Empty, it shows the text passed to toast().

children

Content, or a function of the part's state that returns it.

Type ReactNode | ((state: {}) => ReactNode)

className

Class names, or a function of the part's state that returns them.

Type string | ((state: {}) => string)

render

Renders your own element: one that receives the part's props, or a function of the props and the state.

Type RenderProp<{}>

style

Styles, or a function of the part's state that returns them.

Type CSSProperties | ((state: {}) => CSSProperties)