Alert Dialog

Asks for confirmation before an action that can't be undone.

Unlike a dialog, it can’t be dismissed by pressing outside: the person has to choose. Focus starts on the first AlertDialogClose, so put the safe choice first.

Preview
basic.tsx
import {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "~/components/ui/alert-dialog"
import { Button } from "~/components/ui/button"

export default function Example() {
  return (
    <AlertDialog>
      <AlertDialogTrigger render={<Button variant="destructive" />}>
        Delete edition
      </AlertDialogTrigger>
      <AlertDialogBackdrop />
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Delete the weekend edition?</AlertDialogTitle>
          <AlertDialogDescription>
            Its 24 pages, layouts and checks are deleted. Stories and ads stay in the library.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogClose render={<Button variant="outline" />}>Keep it</AlertDialogClose>
          <AlertDialogClose render={<Button variant="destructive" />}>Delete</AlertDialogClose>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}

Dependencies

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

UsesTextprimitive
Used byNothing yet.
Packages @ui-sdk/core@0.1.0-beta.20@ui-sdk/react@0.1.0-beta.20

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/alert-dialog.json

Manually

Install its packages:

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

Add the components it uses first, listed under Dependencies.

Then copy the source:

components/ui/alert-dialog.tsx
import {
  AlertDialog,
  AlertDialogBackdrop as AlertDialogBackdropPrimitive,
  AlertDialogClose,
  AlertDialogContent as AlertDialogContentPrimitive,
  AlertDialogDescription as AlertDialogDescriptionPrimitive,
  AlertDialogTitle as AlertDialogTitlePrimitive,
  AlertDialogTrigger,
} from "@ui-sdk/react/alert-dialog"
import type * as React from "react"

import { textVariants } from "~/components/ui/text"
import { cn, cnState } from "~/lib/utils"

/** Dims and softly blurs the page behind the confirmation. */
function AlertDialogBackdrop({
  className,
  ...props
}: React.ComponentProps<typeof AlertDialogBackdropPrimitive>) {
  return (
    <AlertDialogBackdropPrimitive
      className={cnState(
        "fixed inset-0 bg-backdrop transition-opacity duration-100 data-ending-style:opacity-0 data-starting-style:opacity-0 supports-backdrop-filter:backdrop-blur-sm motion-reduce:transition-none",
        className,
      )}
      {...props}
    />
  )
}

/**
 * Asks for confirmation before an action, and can't be dismissed by pressing
 * outside. Give it a title, a description, and an `AlertDialogClose` for each choice.
 */
function AlertDialogContent({
  className,
  ...props
}: React.ComponentProps<typeof AlertDialogContentPrimitive>) {
  return (
    <AlertDialogContentPrimitive
      className={cnState(
        [
          textVariants({ size: "sm" }),
          "fixed top-1/2 left-1/2 m-0 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-xl rounded-xl bg-overlay p-xl text-overlay-foreground shadow-xl ring-1 ring-foreground/5 outline-none sm:max-w-md dark:ring-foreground/10",
          "origin-(--transform-origin) transition-[opacity,scale] duration-100 ease-out data-starting-style:scale-95 data-starting-style:opacity-0 data-ending-style:scale-95 data-ending-style:opacity-0 motion-reduce:transition-none",
        ].join(" "),
        className,
      )}
      {...props}
    />
  )
}

/** Groups the title and description. */
function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">) {
  return <div data-slot="alert-dialog-header" className={cn("grid gap-xs", className)} {...props} />
}

/** Holds the choices, the safe one first on small screens. */
function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      data-slot="alert-dialog-footer"
      className={cn("flex flex-col-reverse gap-sm sm:flex-row sm:justify-end", className)}
      {...props}
    />
  )
}

/** States what's about to happen. */
function AlertDialogTitle({
  className,
  ...props
}: React.ComponentProps<typeof AlertDialogTitlePrimitive>) {
  return (
    <AlertDialogTitlePrimitive
      className={cnState(
        textVariants({ size: "md", weight: "medium", family: "heading", leading: "none" }),
        className,
      )}
      {...props}
    />
  )
}

/** Explains the consequences. */
function AlertDialogDescription({
  className,
  ...props
}: React.ComponentProps<typeof AlertDialogDescriptionPrimitive>) {
  return (
    <AlertDialogDescriptionPrimitive
      className={cnState([textVariants({ size: "sm", tone: "muted" })], className)}
      {...props}
    />
  )
}

export {
  AlertDialog,
  AlertDialogBackdrop,
  AlertDialogClose,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
}

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.

AlertDialog

A modal dialog that interrupts the user with something important and waits for an answer, like "Delete this file?".

container

Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.

Type Element | DocumentFragment | null

controller

Opens, closes and inspects the alert dialog from anywhere. Create one with createAlertDialogController() or createConfirm().

Type PopupController<any, AlertDialogOpenChangeReason, {}, any, DialogPayloadChangeReason>

debug

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

Type boolean

defaultOpen

Whether the dialog starts open, when uncontrolled. Focus moves into it once it's on the page.

Type boolean · Default false

dismissible

Whether Escape, an outside press and Android's back gesture can close the dialog. Close parts, triggers and the controller always can. Pass false while a form has unsaved changes, and ask in onDismissAttempt.

Type boolean · Default true

onDismissAttempt

Runs when a dismissal was refused, because dismissible is false, an outside press doesn't close it, or a Close part's action is running. Ask "Discard changes?" here.

Type (details: DialogDismissAttemptDetails) => void

onOpenChange

Runs when the alert dialog wants to open or close. details.reason says why, details.cancel() stops it, and details.returnValue is the value of the Close part that closed it.

Type (open: boolean, details: DialogOpenChangeDetails<AlertDialogOpenChangeReason>) => void

onOpenChangeComplete

Runs once the dialog has finished opening or closing, after any animation.

Type (open: boolean) => void

onPayloadChange

Runs when a trigger or a controller with another payload opens the alert dialog, before onOpenChange, or a controller's open({ payload }) gives the open one another payload. details.cancel() keeps the previous payload.

Type (payload: unknown, details: ChangeDetails<DialogPayloadChangeReason>) => void

open

Whether the dialog is open. Pass it to control the dialog.

Type boolean

pendingAnnouncement

What screen readers hear once a Close part's action has been running 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"

persistentElements

Elements that stay usable while the dialog makes the page inert, like a chat launcher or a password manager's button. Elements, CSS selectors, or a function that returns elements, read when the dialog opens. Presses on them never close it.

Type (string | Element)[] | (() => Element[])

AlertDialogBackdrop

Dims and softly blurs the page behind the confirmation.

children

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

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

className

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

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

render

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

Type RenderProp<DialogBackdropState>

style

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

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

AlertDialogContent

Asks for confirmation before an action, and can't be dismissed by pressing outside. Give it a title, a description, and an AlertDialogClose for each choice.

children

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

Type ReactNode | ((state: DialogContentState<unknown>) => ReactNode)

className

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

Type string | ((state: DialogContentState<unknown>) => string)

container

Renders the popup into this element instead of in place, like a container inside a shadow root or an iframe. On web components, a CSS selector. Nested popups stay inside their parent.

Type Element | DocumentFragment | null

finalFocus

Where focus goes when the dialog closes while focus is inside it.

Type PopupFocusTarget · Default "trigger"

initialFocus

Where focus goes when the dialog opens. Opening with touch focuses the dialog itself, so no on-screen keyboard appears, unless this is set to something other than "auto".

Type DialogInitialFocus · Default "auto"

inline

Renders the dialog and its backdrop where they are in the page instead of above it, so it can stay inside a frame, like an app preview. Pair it with modal="trap-focus" to keep the rest of the page usable. A container on the dialog still moves its backdrop, so leave it off.

Type boolean · Default false

keepMounted

Whether the dialog stays in the page, hidden, while closed. Its content keeps its state between opens.

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<DialogContentState<unknown>>

style

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

Type CSSProperties | ((state: DialogContentState<unknown>) => CSSProperties)

AlertDialogDescription

Explains the consequences.

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)

AlertDialogFooter

Holds the choices, the safe one first on small screens.

Takes the props of a native div.

AlertDialogHeader

Groups the title and description.

Takes the props of a native div.

AlertDialogTitle

States what's about to happen.

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)

AlertDialogTrigger

The button that opens the alert dialog. A trigger outside the alert dialog connects through controller.

children

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

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

className

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

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

controller

Connects a trigger outside the alert dialog to the alert dialog with this controller.

Type PopupController<any, AlertDialogOpenChangeReason, {}, any, DialogPayloadChangeReason>

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

focusableWhenDisabled

Keeps a disabled trigger in the tab order with aria-disabled instead of the native attribute, so it can host a tooltip that says why. Presses still do nothing.

Type boolean · Default false

payload

Data for the content to render when this trigger opens the dialog, like the row it belongs to.

Type unknown

render

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

Type RenderProp<DialogTriggerState>

shortcut

A keyboard shortcut that presses the trigger, like "mod+k". mod is Command on Apple platforms and Control elsewhere. Sets aria-keyshortcuts, and a Shortcut part inside shows it. A modal dialog pauses the page's shortcuts while it's open.

Type string

style

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

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