← Components

Communication · Material 3: Snackbar

Toast

Brief notifications in a corner of the screen, on an inverse surface. A new one melts into the stack. Can also live inside a container.

Examples and variants

Screen corner (default)

Plain, with an action, and a promise toast.

Example
function ToastCorner() {
  return (
    <ToastProvider>
      <Triggers />
      <Toaster position="bottom-end" />
    </ToastProvider>
  )
}

Region variant

ToastRegion scopes toasts to a container.

Example
function ToastInRegion() {
  return (
    <ToastRegion className="flex min-h-40 w-full max-w-sm items-start rounded-(--shape-md) bg-canvas p-3 pb-16 shadow-1">
      <Triggers />
    </ToastRegion>
  )
}

Spec drawing

Measured from the live component at default density. Each code maps to the token that sets it; change the token and the drawing follows.

Install

With the CLI

The shadcn CLI only delivers files: it copies our code from the Isotopi registry into your project and installs the packages it uses. Add the foundation once, then the component.

Terminal
npx shadcn@latest add https://isotopi.com/r/minimal.json
npx shadcn@latest add https://isotopi.com/r/toast.json

By hand

No CLI needed. Add the foundation once (see Getting started), then follow these steps. They include every component this one builds on.

  1. Install the packages it uses.

    Terminal
    npm install @base-ui/react lucide-react
  2. Copy this file to the same paths in your project. Imports use the @/ alias for your project root.

    • components/ui/toast.tsxtoast
      components/ui/toast.tsx
      "use client"
      
      import * as React from "react"
      import { Toast as ToastPrimitive } from "@base-ui/react/toast"
      import { CheckIcon, LoaderCircleIcon, XIcon } from "lucide-react"
      import { GooLayer } from "@/components/motion/goo-layer"
      import { tokenMs } from "@/lib/motion/token-ms"
      import { motionLevel } from "@/lib/overlay"
      
      /*
        Toast (snackbar): brief notifications.
        - Default: <ToastProvider> + <Toaster /> once in the app. Toasts stack in a
          corner of the screen (`position`, default bottom-end).
        - Variant: <ToastRegion> scopes toasts to a container (a card or panel);
          the stack sits at that container's bottom edge.
        Feedback that belongs to a control (saving, copying) stays on the control
        (Button status); toasts are for notifications.
      */
      type ToastPosition = "bottom-end" | "bottom-start" | "bottom-center" | "top-end" | "top-start" | "top-center"
      const positions: Record<ToastPosition, string> = {
        "bottom-end": "fixed bottom-4 end-4 items-end",
        "bottom-start": "fixed bottom-4 start-4 items-start",
        "bottom-center": "fixed inset-x-4 bottom-4 items-center",
        "top-end": "fixed top-4 end-4 items-end",
        "top-start": "fixed top-4 start-4 items-start",
        "top-center": "fixed inset-x-4 top-4 items-center",
      }
      const RegionContext = React.createContext<HTMLDivElement | null>(null)
      
      function ToastProvider({ children, ...props }: ToastPrimitive.Provider.Props) {
        return <ToastPrimitive.Provider {...props}>{children}</ToastPrimitive.Provider>
      }
      
      function ToastRegion({
        children,
        className,
        label = "Notifications",
        ...props
      }: React.ComponentProps<"div"> & { label?: string }) {
        // State, not a ref: the stack portals into this element, so wait until it exists.
        const [node, setNode] = React.useState<HTMLDivElement | null>(null)
        return (
          <ToastPrimitive.Provider>
            <RegionContext.Provider value={node}>
              <div ref={setNode} data-slot="toast-region" className={["relative", className].filter(Boolean).join(" ")} {...props}>
                {children}
                {node ? <Toaster label={label} /> : null}
              </div>
            </RegionContext.Provider>
          </ToastPrimitive.Provider>
        )
      }
      
      function Toaster({ label = "Notifications", position = "bottom-end" }: { label?: string; position?: ToastPosition }) {
        const region = React.useContext(RegionContext)
        const { toasts } = ToastPrimitive.useToastManager()
        const [merge, setMerge] = React.useState(false)
        const previous = React.useRef(0)
      
        React.useEffect(() => {
          if (toasts.length > previous.current && motionLevel(region) === "liquid") {
            setMerge(true)
            const timer = window.setTimeout(() => setMerge(false), tokenMs("--goo-duration"))
            previous.current = toasts.length
            return () => window.clearTimeout(timer)
          }
          previous.current = toasts.length
        }, [toasts.length, region])
      
        return (
          <ToastPrimitive.Portal container={region ?? undefined}>
            <ToastPrimitive.Viewport
              aria-label={label}
              data-position={region ? "region" : position}
              className={[
                "pointer-events-none z-toast flex flex-col gap-2 outline-none *:pointer-events-auto *:w-full *:max-w-(--layout-toast)",
                region ? "absolute inset-x-3 bottom-3 items-center" : `${positions[position]} w-(--layout-toast) max-w-[calc(100vw-var(--space-8))]`,
              ].join(" ")}
            >
              {merge ? <ToastMerge /> : null}
              {toasts.map((toast) => (
                <ToastPrimitive.Root
                  key={toast.id}
                  toast={toast}
                  data-slot="toast"
                  className="toast-card relative rounded-(--toast-corner) bg-(--toast-container) px-(--toast-padding-x) py-(--toast-padding-y) text-sm text-(--toast-label) shadow-(--toast-elevation)"
                >
                  <ToastPrimitive.Content className="flex items-start justify-between gap-3">
                    <ToastMark type={toast.type} />
                    <div className="flex flex-1 flex-col gap-0.5">
                      <ToastPrimitive.Title className="font-medium" />
                      <ToastPrimitive.Description className="text-(--toast-supporting)" />
                    </div>
                    {toast.actionProps ? (
                      <ToastPrimitive.Action className="liquid-press h-6 rounded-(--radius-pill) px-2 text-sm font-medium text-(--toast-label) outline-none hover:bg-[color-mix(in_oklch,var(--toast-label)_14%,transparent)] focus-visible:shadow-(--focus-ring)" />
                    ) : null}
                    <ToastPrimitive.Close
                      aria-label="Dismiss"
                      className="liquid-press inline-flex size-6 items-center justify-center rounded-(--radius-pill) text-(--toast-supporting) outline-none hover:bg-[color-mix(in_oklch,var(--toast-label)_14%,transparent)] focus-visible:shadow-(--focus-ring)"
                    >
                      <XIcon aria-hidden className="size-(--size-icon-sm)" />
                    </ToastPrimitive.Close>
                  </ToastPrimitive.Content>
                </ToastPrimitive.Root>
              ))}
            </ToastPrimitive.Viewport>
          </ToastPrimitive.Portal>
        )
      }
      
      function ToastMark({ type }: { type?: string }) {
        if (type !== "loading" && type !== "success" && type !== "error") return null
        return (
          <span className="relative mt-0.5 size-icon-sm shrink-0">
            <LoaderCircleIcon
              aria-hidden
              className="icon-spin absolute inset-0 size-icon-sm text-(--toast-supporting)"
              style={{ opacity: type === "loading" ? 1 : 0 }}
            />
            <CheckIcon
              aria-hidden
              className="icon-morph absolute inset-0 size-icon-sm text-(--toast-label)"
              style={{ opacity: type === "success" ? 1 : 0, scale: type === "success" ? 1 : 0.6 }}
            />
            <XIcon
              aria-hidden
              className="icon-morph absolute inset-0 size-icon-sm text-(--color-danger)"
              style={{ opacity: type === "error" ? 1 : 0, scale: type === "error" ? 1 : 0.6 }}
            />
          </span>
        )
      }
      
      function ToastMerge() {
        const hostRef = React.useRef<HTMLSpanElement>(null)
        React.useLayoutEffect(() => {
          const host = hostRef.current
          const viewport = host?.parentElement
          if (!host || !viewport) return
          const cards = [...viewport.querySelectorAll<HTMLElement>("[data-slot=toast]")].slice(0, 2)
          if (cards.length < 2) return
          const frame = viewport.getBoundingClientRect()
          const boxes = cards.map((card) => {
            const box = card.getBoundingClientRect()
            return {
              x: box.left - frame.left,
              y: box.top - frame.top,
              width: box.width,
              height: box.height,
            }
          })
          const [front, back] = boxes
          if (!front || !back) return
          host.style.left = "0px"
          host.style.top = "0px"
          host.style.width = `${frame.width}px`
          host.style.height = `${frame.height}px`
          const svg = host.querySelector("svg")
          svg?.setAttribute("viewBox", `0 0 ${frame.width} ${frame.height}`)
          const rects = host.querySelectorAll("rect")
          rects[0]?.setAttribute("x", String(front.x))
          rects[0]?.setAttribute("y", String(front.y))
          rects[0]?.setAttribute("width", String(front.width))
          rects[0]?.setAttribute("height", String(front.height))
          rects[1]?.setAttribute("x", String(back.x))
          rects[1]?.setAttribute("y", String(back.y))
          rects[1]?.setAttribute("width", String(back.width))
          rects[1]?.setAttribute("height", String(back.height))
        })
        return (
          <span ref={hostRef} className="toast-goo pointer-events-none absolute">
            <GooLayer width="100%" height="100%" viewBox="0 0 320 96" className="overflow-visible">
              <rect x="24" y="40" width="272" height="48" rx="24" fill="var(--toast-container)" />
              <rect x="48" y="8" width="224" height="44" rx="22" fill="var(--toast-container)" />
            </GooLayer>
          </span>
        )
      }
      
      function useToast() {
        return ToastPrimitive.useToastManager()
      }
      
      export { ToastProvider, ToastRegion, Toaster, useToast }
      

Imports

What the examples on this page import:

Imports
import { Button } from "@/components/ui/button"
import { ToastProvider, ToastRegion, Toaster, useToast } from "@/components/ui/toast"
import { tokenMs } from "@/lib/motion/token-ms"

Anatomy

  1. 1Container · --toast-container (inverse), --toast-corner, --toast-padding-*, --toast-elevation, --toast-width.
  2. 2Title and description · --toast-label and --toast-supporting.
  3. 3Action · One short action, like Undo.
  4. 4Close · Dismiss button.

Props

PropTypeDefaultDescription
Toaster position"bottom-end" | "bottom-start" | "bottom-center" | "top-end" | "top-start" | "top-center""bottom-end"Corner of the screen.
useToast().add({ title, description, actionProps, timeout })—Show a toast.
useToast().promise(promise, { loading, success, error })—One toast that follows a promise.
ToastRegionwrapper—Variant: toasts stack at that container's bottom edge.

Tokens

Every visual spec is a component token in styles/tokens/components.css, pointing at a semantic token. Change a token to restyle the component; themes change the semantic layer.

TokenPoints toLightDark
--toast-containervar(--surface-inverse)oklch(0.22 0.01 260)oklch(0.95 0 0)
--toast-labelvar(--on-surface-inverse)oklch(0.98 0.004 95)oklch(0.14 0 0)
--toast-supportingcolor-mix(in oklch, var(--on-surface-inverse) 72%, transparent)color-mix(in oklch, var(--on-surface-inverse) 72%, transparent)same
--toast-cornervar(--shape-md)14pxsame
--toast-padding-xvar(--space-4)16pxsame
--toast-padding-yvar(--space-3)12pxsame
--toast-widthvar(--layout-toast)360pxsame
--toast-elevationvar(--elevation-3)0 1px 1px -0.5px oklch(0.22 0.01 260 / 8%), 0 3px 3px -1.5px oklch(0.22 0.01 260 / 8%), 0 6px 6px -3px oklch(0.22 0.01 260 / 8%), 0 12px 12px -6px oklch(0.22 0.01 260 / 8%), 0 24px 24px -12px oklch(0.22 0.01 260 / 8%), 0 48px 48px -24px oklch(0.22 0.01 260 / 6%)0 8px 20px oklch(0 0 0 / 45%), 0 20px 44px oklch(0 0 0 / 40%)

Motion

TriggerWhat happensTokens
EnterRises past its rest point and settles; blur clears.--duration-signature, --ease-bounce
StackA new toast melts into the stack with goo.--goo-duration
DismissSwipe sideways, or it shrinks away when the timer ends.--duration-fast

Calm keeps the motion without overshoot. Still (and reduced motion) keeps a designed frame with no movement.

Accessibility

  • Polite live region.
  • Timers pause on hover and focus.
  • Actions are reachable by keyboard; never the only way to see an error.

Usage

Do

  • Use for brief notifications and Undo.

Don’t

  • Don't use for saving or copying (use Button status).
  • Don't use for errors that need action (use Alert or Dialog).

Code

components/ui/toast.tsx
"use client"

import * as React from "react"
import { Toast as ToastPrimitive } from "@base-ui/react/toast"
import { CheckIcon, LoaderCircleIcon, XIcon } from "lucide-react"
import { GooLayer } from "@/components/motion/goo-layer"
import { tokenMs } from "@/lib/motion/token-ms"
import { motionLevel } from "@/lib/overlay"

/*
  Toast (snackbar): brief notifications.
  - Default: <ToastProvider> + <Toaster /> once in the app. Toasts stack in a
    corner of the screen (`position`, default bottom-end).
  - Variant: <ToastRegion> scopes toasts to a container (a card or panel);
    the stack sits at that container's bottom edge.
  Feedback that belongs to a control (saving, copying) stays on the control
  (Button status); toasts are for notifications.
*/
type ToastPosition = "bottom-end" | "bottom-start" | "bottom-center" | "top-end" | "top-start" | "top-center"
const positions: Record<ToastPosition, string> = {
  "bottom-end": "fixed bottom-4 end-4 items-end",
  "bottom-start": "fixed bottom-4 start-4 items-start",
  "bottom-center": "fixed inset-x-4 bottom-4 items-center",
  "top-end": "fixed top-4 end-4 items-end",
  "top-start": "fixed top-4 start-4 items-start",
  "top-center": "fixed inset-x-4 top-4 items-center",
}
const RegionContext = React.createContext<HTMLDivElement | null>(null)

function ToastProvider({ children, ...props }: ToastPrimitive.Provider.Props) {
  return <ToastPrimitive.Provider {...props}>{children}</ToastPrimitive.Provider>
}

function ToastRegion({
  children,
  className,
  label = "Notifications",
  ...props
}: React.ComponentProps<"div"> & { label?: string }) {
  // State, not a ref: the stack portals into this element, so wait until it exists.
  const [node, setNode] = React.useState<HTMLDivElement | null>(null)
  return (
    <ToastPrimitive.Provider>
      <RegionContext.Provider value={node}>
        <div ref={setNode} data-slot="toast-region" className={["relative", className].filter(Boolean).join(" ")} {...props}>
          {children}
          {node ? <Toaster label={label} /> : null}
        </div>
      </RegionContext.Provider>
    </ToastPrimitive.Provider>
  )
}

function Toaster({ label = "Notifications", position = "bottom-end" }: { label?: string; position?: ToastPosition }) {
  const region = React.useContext(RegionContext)
  const { toasts } = ToastPrimitive.useToastManager()
  const [merge, setMerge] = React.useState(false)
  const previous = React.useRef(0)

  React.useEffect(() => {
    if (toasts.length > previous.current && motionLevel(region) === "liquid") {
      setMerge(true)
      const timer = window.setTimeout(() => setMerge(false), tokenMs("--goo-duration"))
      previous.current = toasts.length
      return () => window.clearTimeout(timer)
    }
    previous.current = toasts.length
  }, [toasts.length, region])

  return (
    <ToastPrimitive.Portal container={region ?? undefined}>
      <ToastPrimitive.Viewport
        aria-label={label}
        data-position={region ? "region" : position}
        className={[
          "pointer-events-none z-toast flex flex-col gap-2 outline-none *:pointer-events-auto *:w-full *:max-w-(--layout-toast)",
          region ? "absolute inset-x-3 bottom-3 items-center" : `${positions[position]} w-(--layout-toast) max-w-[calc(100vw-var(--space-8))]`,
        ].join(" ")}
      >
        {merge ? <ToastMerge /> : null}
        {toasts.map((toast) => (
          <ToastPrimitive.Root
            key={toast.id}
            toast={toast}
            data-slot="toast"
            className="toast-card relative rounded-(--toast-corner) bg-(--toast-container) px-(--toast-padding-x) py-(--toast-padding-y) text-sm text-(--toast-label) shadow-(--toast-elevation)"
          >
            <ToastPrimitive.Content className="flex items-start justify-between gap-3">
              <ToastMark type={toast.type} />
              <div className="flex flex-1 flex-col gap-0.5">
                <ToastPrimitive.Title className="font-medium" />
                <ToastPrimitive.Description className="text-(--toast-supporting)" />
              </div>
              {toast.actionProps ? (
                <ToastPrimitive.Action className="liquid-press h-6 rounded-(--radius-pill) px-2 text-sm font-medium text-(--toast-label) outline-none hover:bg-[color-mix(in_oklch,var(--toast-label)_14%,transparent)] focus-visible:shadow-(--focus-ring)" />
              ) : null}
              <ToastPrimitive.Close
                aria-label="Dismiss"
                className="liquid-press inline-flex size-6 items-center justify-center rounded-(--radius-pill) text-(--toast-supporting) outline-none hover:bg-[color-mix(in_oklch,var(--toast-label)_14%,transparent)] focus-visible:shadow-(--focus-ring)"
              >
                <XIcon aria-hidden className="size-(--size-icon-sm)" />
              </ToastPrimitive.Close>
            </ToastPrimitive.Content>
          </ToastPrimitive.Root>
        ))}
      </ToastPrimitive.Viewport>
    </ToastPrimitive.Portal>
  )
}

function ToastMark({ type }: { type?: string }) {
  if (type !== "loading" && type !== "success" && type !== "error") return null
  return (
    <span className="relative mt-0.5 size-icon-sm shrink-0">
      <LoaderCircleIcon
        aria-hidden
        className="icon-spin absolute inset-0 size-icon-sm text-(--toast-supporting)"
        style={{ opacity: type === "loading" ? 1 : 0 }}
      />
      <CheckIcon
        aria-hidden
        className="icon-morph absolute inset-0 size-icon-sm text-(--toast-label)"
        style={{ opacity: type === "success" ? 1 : 0, scale: type === "success" ? 1 : 0.6 }}
      />
      <XIcon
        aria-hidden
        className="icon-morph absolute inset-0 size-icon-sm text-(--color-danger)"
        style={{ opacity: type === "error" ? 1 : 0, scale: type === "error" ? 1 : 0.6 }}
      />
    </span>
  )
}

function ToastMerge() {
  const hostRef = React.useRef<HTMLSpanElement>(null)
  React.useLayoutEffect(() => {
    const host = hostRef.current
    const viewport = host?.parentElement
    if (!host || !viewport) return
    const cards = [...viewport.querySelectorAll<HTMLElement>("[data-slot=toast]")].slice(0, 2)
    if (cards.length < 2) return
    const frame = viewport.getBoundingClientRect()
    const boxes = cards.map((card) => {
      const box = card.getBoundingClientRect()
      return {
        x: box.left - frame.left,
        y: box.top - frame.top,
        width: box.width,
        height: box.height,
      }
    })
    const [front, back] = boxes
    if (!front || !back) return
    host.style.left = "0px"
    host.style.top = "0px"
    host.style.width = `${frame.width}px`
    host.style.height = `${frame.height}px`
    const svg = host.querySelector("svg")
    svg?.setAttribute("viewBox", `0 0 ${frame.width} ${frame.height}`)
    const rects = host.querySelectorAll("rect")
    rects[0]?.setAttribute("x", String(front.x))
    rects[0]?.setAttribute("y", String(front.y))
    rects[0]?.setAttribute("width", String(front.width))
    rects[0]?.setAttribute("height", String(front.height))
    rects[1]?.setAttribute("x", String(back.x))
    rects[1]?.setAttribute("y", String(back.y))
    rects[1]?.setAttribute("width", String(back.width))
    rects[1]?.setAttribute("height", String(back.height))
  })
  return (
    <span ref={hostRef} className="toast-goo pointer-events-none absolute">
      <GooLayer width="100%" height="100%" viewBox="0 0 320 96" className="overflow-visible">
        <rect x="24" y="40" width="272" height="48" rx="24" fill="var(--toast-container)" />
        <rect x="48" y="8" width="224" height="44" rx="22" fill="var(--toast-container)" />
      </GooLayer>
    </span>
  )
}

function useToast() {
  return ToastPrimitive.useToastManager()
}

export { ToastProvider, ToastRegion, Toaster, useToast }