Form dialog
A create or edit form in a dialog: a centred card on desktop, a bottom sheet on phones, with keyboard submit.
It has no trigger part: open it from your own button with open and onOpenChange. On phones it is a sheet from the bottom, and the default footer folds into the header: Cancel on the left, the submit button on the right. The Create more switch is in the desktop footer only.
Create form
No project created yet
"use client"
import { useState } from "react"
import { FolderPlusIcon } from "@keyline-icons/react"
import { Button } from "@/components/ui/button"
import { FormDialog, FormField } from "@/components/ui/form-dialog"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { useActionStatus } from "@/hooks/use-action-status"
// Stands in for the product's request: it takes a second and refuses a name that is in use.
function createProject(name: string) {
return new Promise<string>((resolve, reject) => {
setTimeout(() => {
if (name.toLowerCase() === "website refresh") reject(new Error(`A project named ${name} already exists.`))
else resolve(name)
}, 1000)
})
}
export default function FormDialogCreateForm() {
const [open, setOpen] = useState(false)
const [error, setError] = useState<string>()
const [created, setCreated] = useState<string>()
const save = useActionStatus()
return (
<div className="flex flex-col items-center gap-3">
<Button variant="outline" onClick={() => setOpen(true)}>
New project
</Button>
<p role="status" className="text-muted-foreground">
{created ? `Created ${created}` : "No project created yet"}
</p>
<FormDialog
open={open}
onOpenChange={(next) => {
// The request cannot be cancelled, so the dialog stays until it settles.
if (next || save.status !== "pending") setOpen(next)
}}
onOpenChangeComplete={(isOpen) => {
if (isOpen) document.getElementById("new-project-name")?.focus()
else setError(undefined)
}}
icon={<FolderPlusIcon />}
title="New project"
description="Name the project and say what it is for."
formId="new-project"
submitLabel="Create"
submitKbd
pending={save.status === "pending"}
size="sm"
>
<form
id="new-project"
className="contents"
onSubmit={async (event) => {
event.preventDefault()
const name = String(new FormData(event.currentTarget).get("name")).trim()
setError(undefined)
try {
setCreated(await save.run(createProject(name)))
setOpen(false)
} catch (reason) {
setError(reason instanceof Error ? reason.message : "The project could not be created.")
}
}}
>
<FormField
label="Name"
htmlFor="new-project-name"
hint={
error ? (
<span id="new-project-error" role="alert" className="text-destructive">
{error}
</span>
) : (
"Website refresh is taken: try it to see the error."
)
}
>
<Input
id="new-project-name"
name="name"
autoComplete="off"
required
aria-invalid={error ? true : undefined}
aria-describedby={error ? "new-project-error" : undefined}
/>
</FormField>
<FormField label="Description" optional htmlFor="new-project-description">
<Textarea id="new-project-description" name="description" />
</FormField>
</form>
</FormDialog>
</div>
)
}
Sizes
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { FormDialog, FormField, FormRow } from "@/components/ui/form-dialog"
import { Input } from "@/components/ui/input"
const sizes = [
{ size: "sm", label: "Small", width: "480px" },
{ size: "md", label: "Medium", width: "640px" },
{ size: "lg", label: "Large", width: "808px" },
] as const
export default function FormDialogSizes() {
const [open, setOpen] = useState(false)
const [choice, setChoice] = useState<(typeof sizes)[number]>(sizes[1])
return (
<div className="flex flex-wrap items-center justify-center gap-2">
{sizes.map((option) => (
<Button
key={option.size}
variant="outline"
onClick={() => {
setChoice(option)
setOpen(true)
}}
>
{option.label}
</Button>
))}
<FormDialog
open={open}
onOpenChange={setOpen}
title="Edit invoice"
description={`The ${choice.label.toLowerCase()} dialog is ${choice.width} wide on desktop.`}
showDescription
size={choice.size}
onSubmit={() => setOpen(false)}
>
<FormRow>
<FormField label="Number" htmlFor="edit-invoice-number">
<Input id="edit-invoice-number" defaultValue="1042" inputMode="numeric" />
</FormField>
<FormField label="Due" htmlFor="edit-invoice-due">
<Input id="edit-invoice-due" type="date" defaultValue="2026-12-04" />
</FormField>
</FormRow>
<FormField label="Reference" optional htmlFor="edit-invoice-reference">
<Input id="edit-invoice-reference" defaultValue="Second milestone" />
</FormField>
</FormDialog>
</div>
)
}
Create more
No tasks added yet
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { FormDialog, FormField } from "@/components/ui/form-dialog"
import { Input } from "@/components/ui/input"
import { useActionStatus } from "@/hooks/use-action-status"
export default function FormDialogCreateMore() {
const [open, setOpen] = useState(false)
const [more, setMore] = useState(true)
const [tasks, setTasks] = useState<string[]>([])
const save = useActionStatus()
return (
<div className="flex flex-col items-center gap-3">
<Button variant="outline" onClick={() => setOpen(true)}>
New task
</Button>
<p role="status" className="text-muted-foreground">
{tasks.length === 0 ? "No tasks added yet" : `Added: ${tasks.join(", ")}`}
</p>
<FormDialog
open={open}
onOpenChange={setOpen}
onOpenChangeComplete={(isOpen) => {
if (isOpen) document.getElementById("new-task-title")?.focus()
}}
title="New task"
description="Add one task, or keep the dialog open to add several."
formId="new-task"
submitLabel="Add"
submitKbd
pending={save.status === "pending"}
createMore={{ checked: more, onCheckedChange: setMore, focusId: "new-task-title" }}
size="sm"
>
<form
id="new-task"
className="contents"
onSubmit={async (event) => {
event.preventDefault()
const form = event.currentTarget
const title = String(new FormData(form).get("title")).trim()
// Stands in for the product's request.
await save.run(new Promise((resolve) => setTimeout(resolve, 600)))
setTasks((current) => [...current, title])
if (more) form.reset()
else setOpen(false)
}}
>
<FormField label="Title" htmlFor="new-task-title">
<Input id="new-task-title" name="title" autoComplete="off" required />
</FormField>
</form>
</FormDialog>
</div>
)
}
Destructive submit
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { FormDialog, FormField } from "@/components/ui/form-dialog"
import { Input } from "@/components/ui/input"
const project = "Website refresh"
export default function FormDialogDestructiveSubmit() {
const [open, setOpen] = useState(false)
const [typed, setTyped] = useState("")
return (
<div>
<Button variant="outline" onClick={() => setOpen(true)}>
Delete project
</Button>
<FormDialog
open={open}
onOpenChange={setOpen}
onOpenChangeComplete={(isOpen) => {
if (!isOpen) setTyped("")
}}
title="Delete project"
description={`This deletes ${project} with its 48 tasks and 12 files. It cannot be undone.`}
showDescription
submitLabel="Delete project"
submitVariant="destructive"
submitDisabled={typed !== project}
submitDescribedBy="delete-project-hint"
onSubmit={() => setOpen(false)}
size="sm"
>
<FormField
label="Project name"
htmlFor="delete-project-name"
hint={<span id="delete-project-hint">Type {project} to confirm.</span>}
>
<Input
id="delete-project-name"
value={typed}
onChange={(event) => setTyped(event.target.value)}
autoComplete="off"
/>
</FormField>
</FormDialog>
</div>
)
}
With tabs
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { FormDialog, FormField, FormRow } from "@/components/ui/form-dialog"
import { Input } from "@/components/ui/input"
import { SegmentedToggleGroup } from "@/components/ui/segmented-toggle-group"
import { Textarea } from "@/components/ui/textarea"
import { ToggleGroupItem } from "@/components/ui/toggle-group"
export default function FormDialogWithTabs() {
const [open, setOpen] = useState(false)
const [section, setSection] = useState(["details"])
return (
<div>
<Button variant="outline" onClick={() => setOpen(true)}>
Edit project
</Button>
<FormDialog
open={open}
onOpenChange={setOpen}
title="Edit project"
description="Change the project's details or how it is billed."
tabs={
<SegmentedToggleGroup
aria-label="Section"
value={section}
// Pressing the selected segment again would clear it: keep one selected.
onValueChange={(next) => next.length > 0 && setSection(next)}
>
<ToggleGroupItem value="details">Details</ToggleGroupItem>
<ToggleGroupItem value="billing">Billing</ToggleGroupItem>
</SegmentedToggleGroup>
}
onSubmit={() => setOpen(false)}
>
{section.includes("details") ? (
<>
<FormField label="Name" htmlFor="edit-project-name">
<Input id="edit-project-name" defaultValue="Website refresh" autoComplete="off" />
</FormField>
<FormField label="Description" optional htmlFor="edit-project-description">
<Textarea
id="edit-project-description"
defaultValue="New pricing page, new navigation and a faster checkout."
/>
</FormField>
</>
) : (
<FormRow>
<FormField label="Hourly rate" htmlFor="edit-project-rate" hint="In euros, before tax.">
<Input id="edit-project-rate" defaultValue="120" inputMode="decimal" />
</FormField>
<FormField label="Budget" optional htmlFor="edit-project-budget" hint="In hours.">
<Input id="edit-project-budget" defaultValue="80" inputMode="numeric" />
</FormField>
</FormRow>
)}
</FormDialog>
</div>
)
}
Custom footer
Nothing saved yet
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { FancyButton } from "@/components/ui/fancy-button"
import { FormDialog, FormField } from "@/components/ui/form-dialog"
import { Input } from "@/components/ui/input"
export default function FormDialogCustomFooter() {
const [open, setOpen] = useState(false)
const [saved, setSaved] = useState("Nothing saved yet")
function finish(result: string) {
setSaved(result)
setOpen(false)
}
return (
<div className="flex flex-col items-center gap-3">
<Button variant="outline" onClick={() => setOpen(true)}>
New invoice
</Button>
<p role="status" className="text-muted-foreground">
{saved}
</p>
<FormDialog
open={open}
onOpenChange={setOpen}
title="New invoice"
description="Save the invoice as a draft or send it now."
size="sm"
// Phones keep the confirm button in the header, so the primary action is wired here too.
submitLabel="Send"
onSubmit={() => finish("Invoice sent")}
footer={
<>
<FancyButton onClick={() => finish("Invoice saved as a draft")}>Save as draft</FancyButton>
<FancyButton variant="primary" onClick={() => finish("Invoice sent")}>
Send
</FancyButton>
</>
}
>
<FormField label="Client" htmlFor="new-invoice-client">
<Input id="new-invoice-client" defaultValue="Website refresh" autoComplete="off" />
</FormField>
<FormField label="Amount" htmlFor="new-invoice-amount" hint="In euros, before tax.">
<Input id="new-invoice-amount" defaultValue="2480" inputMode="decimal" />
</FormField>
</FormDialog>
</div>
)
}
Installation
npx shadcn@latest add @khaeli/form-dialogbunx --bun shadcn@latest add @khaeli/form-dialogInstall @khaeli/foundation first: this item's styling lives in its tokens and [data-slot] rules.
Installs with
- Registry items
- npm packages
- @base-ui/react ^1.7.0
- @keyline-icons/react ^2.2.0
Keyboard
EnterSpace- On your button, opens the dialog. Focus starts on the close button in the header (Cancel on phones), not on the first field: the first and third examples move it to the field in
onOpenChangeComplete. ⌘ EnterCtrl Enter- Submit from anywhere in the dialog: they call
onSubmit, or submit the form named byformId. Nothing happens whilependingorsubmitDisabledis set.submitKbdshows the keys on the button. Enter- In a single-line field of the form named by
formId, submits it, as in any form. TabShift Tab- Move through the header, the fields and the footer, and wrap at either end. Focus cannot leave the dialog while it is open.
Escape- Closes the dialog and returns focus to the button that opened it. It also closes while
pending: only Cancel is disabled then, so keep the dialog open inonOpenChangewhen the request cannot be cancelled, as the first example does.
Accessible name
- The dialog is named by
title.descriptionis always its description for assistive technology and is only shown withshowDescription, so write one either way. FormFieldties its label to the control throughhtmlFor: give the control the sameid.optionaladds the word to the label.- There is no error part. Mark the field with
aria-invalid, pointaria-describedbyat the message and give the messagerole="alert", as the first example does inhint. - While
pendingthe submit button stays focusable, is markedaria-disabledand shows a loader.submitDisableddisables it outright: passsubmitDescribedBythe id of the text that says why. - On phones a submit button labelled Save, Create, Done or Add becomes a check icon and keeps the label as its
aria-label. Any other label stays as text. - With a custom
footer, phones still show the submit button in the header. Give itsubmitLabelandonSubmit(orformId), or it does nothing.
Registry JSON
The item as the shadcn CLI reads it, with every file it ships: https://ui.khaeli.com/r/form-dialog.json