HextaUI

Alert dialog: Controlled

Pass open and onOpenChange to open it from code, without a trigger. Focus still lands on Cancel.

"use client"

import * as React from "react"

import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/components/ui/alert-dialog"
import { Button } from "@/components/ui/button"

export function AlertDialogControlled() {
  const [open, setOpen] = React.useState(false)

  return (
    <>
      <Button
        variant="outline"
        onClick={() => window.setTimeout(() => setOpen(true), 600)}
      >
        Open in 600ms
      </Button>
      <AlertDialog open={open} onOpenChange={setOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Session expiring</AlertDialogTitle>
            <AlertDialogDescription>
              You’ve been inactive for a while. Stay signed in?
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Sign out</AlertDialogCancel>
            <AlertDialogAction>Stay signed in</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  )
}

This adds the example as components/examples/alert-dialog/controlled.tsx, together with the Alert dialog component and the HextaUI theme tokens it needs.

pnpm dlx shadcn@latest add https://hextaui.com/r/alert-dialog-controlled.json

To add only the component, follow the Alert dialog installation.

Props in this example

The Alert dialog props this example sets, from the API reference.

PropTypeDefault
open
boolean–
onOpenChangeNot called for closes blocked by a pending action.
(open: boolean, details) => void–

Every prop is in the Alert dialog API reference.

See them all, with keyboard support and accessibility notes, on the Alert dialog page.