Dialog

updated

We need to talk. A modal window with a header, a scrolling body and a footer. Open it from a template or straight from code.

Demo

Installation

Usage

<script setup lang="ts">
import { Button } from '@/components/ui/button'
import {
  Dialog,
  DialogBody,
  DialogClose,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
</script>

<template>
  <Dialog>
    <DialogTrigger as-child>
      <Button>Edit profile</Button>
    </DialogTrigger>
    <DialogContent>
      <DialogHeader>
        <DialogTitle>Edit profile</DialogTitle>
        <DialogDescription>Changes are saved when you press Save.</DialogDescription>
      </DialogHeader>
      <DialogBody>
        <!-- the content -->
      </DialogBody>
      <DialogFooter>
        <DialogClose as-child>
          <Button>Save</Button>
        </DialogClose>
      </DialogFooter>
    </DialogContent>
  </Dialog>
</template>
  • Dialog: holds the state; v-model:open opens it from code
  • DialogTrigger: opens it
  • DialogContent: the window, with an overlay and a close button
  • DialogHeader, DialogBody, DialogFooter: the three parts
  • DialogClose: wrap any button in it to make it close the dialog

Putting a form inside? Wrap the parts in <form class="contents">, so the layout and scrolling keep working.

Escape or a click outside closes it. Focus stays inside while it's open, lands on the first field rather than the close button, and returns to the trigger when the dialog closes. More on overlays.

Too much content? The body scrolls, and the header and footer stay put.

Examples

Long content

Once the window reaches the edge of the screen, the body scrolls between the header and the footer.

Body scroll

Scroll area

Want the thin ScrollArea scrollbar instead of the browser's? Let the scroll area take the rest of the window with flex-1: the window grows with the list until it reaches the edge of the screen, and the list scrolls from there.

Scroll area

Scrolling overlay

Long read? Use DialogScrollContent instead of DialogContent: the window keeps its full height, and the whole thing scrolls like a page.

Don't turn off modal here, or nothing renders at all.

Scroll overlay

Fullscreen

No special prop, just classes. Add these to DialogContent, and the window fills the screen:

inset-0 size-full max-h-none max-w-none translate-none rounded-none border-0

Fullscreen

Not dismissible

No escape. Literally. Prevent escape-key-down and interact-outside on DialogContent, and only a button inside can close it. Add :show-close-button="false" to hide the close button too.

Dismissible

Nested

Yo dawg, I heard you like dialogs. Open one from inside another, and it stacks on top. Only the top one dims the page, and Escape or a click outside closes only that one.

In the demo, the inner dialog confirms a change, and the first one stays open with the result.

Nested

Custom layout

The parts are plain elements with classes, so any of them can be restyled or left out. This confirmation centres its header and drops the close button.

Custom

Controlled

Without a trigger, bind v-model:open and open the dialog from anywhere in the component. Here it opens from a menu item. To open a dialog without placing it in a template at all, see From code.

Controlled

quarterly-report.pdf

From code

No template? No problem. Open a dialog from a store, a router guard or a callback, and await how it closed.

Setup

Install it once:

// main.ts
import { createApp } from 'vue'

import { createDialogs } from '@/components/ui/dialog'
import App from './App.vue'

createApp(App).use(createDialogs()).mount('#app')

In Nuxt, use a plugin:

// plugins/dialogs.ts
import { createDialogs } from '@/components/ui/dialog'

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.use(createDialogs())
})

Add one DialogHost to the root component. Dialogs opened from code render there, so they can use the router, i18n and stores:

<!-- App.vue -->
<script setup lang="ts">
import { DialogHost } from '@/components/ui/dialog'
</script>

<template>
  <RouterView />
  <DialogHost />
</template>

Opening a dialog

Write a component that renders DialogContent, just like in a template. useDialogContext() gives it close(value) and dismiss():

<!-- DeleteFileDialog.vue -->
<script setup lang="ts">
import { Button } from '@/components/ui/button'
import {
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  useDialogContext,
} from '@/components/ui/dialog'

const props = defineProps<{ name: string }>()

const { close, dismiss } = useDialogContext()
</script>

<template>
  <DialogContent class="max-w-sm">
    <DialogHeader>
      <DialogTitle>Delete {{ props.name }}?</DialogTitle>
      <DialogDescription>The file moves to the bin for 30 days.</DialogDescription>
    </DialogHeader>
    <DialogFooter>
      <Button variant="outline" color="neutral" @click="dismiss()">Cancel</Button>
      <Button color="destructive" @click="close()">Delete</Button>
    </DialogFooter>
  </DialogContent>
</template>

Then open it and wait:

const result = await openDialog(DeleteFileDialog, { name: 'report.pdf' })

if (result.ok) deleteFile()

The promise never rejects. After close(value), result.ok is true and you get result.value. Otherwise it's false, and result.reason says why:

Programmatic

report.pdf is in your files.

ReasonWhat happened
escapeEscape was pressed
outsideA click or focus landed outside
swipeA drawer was swiped away
close-buttonA DialogClose was pressed
programmaticdismiss() was called
close-allcloseAllDialogs() was called
unmountDialogHost unmounted
no-hostNo service or no DialogHost. Resolves at once, with a console warning
errorIt failed to render. The error also goes to app.config.errorHandler

The promise is also a handle: isOpen, close(value) and dismiss() work from outside, and patch(props) updates the props on the fly. Only the first close counts.

One dialog, many calls

defineDialog(component, { props }) sets the component and default props once. Each open(props) merges new props over the defaults. Calling open() while the dialog is already open returns the same one, not a second window. isOpen and dismiss() work from anywhere.

In the demo, the caller updates the progress while the dialog is open:

Define

12 photos selected.

Closing with a value? Type it on both sides: useDialogContext<string>() inside, open<string>() outside. openDialog<string>() works too, but then the props go unchecked. defineDialog checks both.

Waiting for work

While loading from useDialogContext() is true, Escape, outside clicks and DialogClose do nothing. Only close() or dismiss() can close it. Disable the buttons too, so nobody starts the work twice.

Async

Aurora

Keeping state

With keepMounted: true, a defined dialog is hidden instead of removed, so its state survives until the next open. Each open still gets its own promise.

Keep mounted

Nothing sent yet.

Closing everything

closeAllDialogs() closes them all. Dialogs survive navigation, so to close them on every route change:

router.afterEach(() => closeAllDialogs())

API Reference

Every part except Dialog, which renders no element, accepts class, merged over its own classes with tailwind-merge. On DialogContent and DialogScrollContent it styles the window, so a width class such as max-w-2xl resizes it.

Data attributes

data-slotAttributesDescription
dialog-triggerdata-stateThe element that opens the dialog.
dialog-overlaydata-stateThe layer behind the window that dims the page and takes outside presses. Under another open dialog it turns clear, so a stack dims the page once.
dialog-contentdata-stateThe window.
dialog-header—The title and description.
dialog-title—The title.
dialog-description—The description.
dialog-body—The scrolling middle.
dialog-footer—The buttons at the bottom.
dialog-close—The close button, or any DialogClose.

Accessibility

The dialog's name comes from its DialogTitle and its description from its DialogDescription. Always give it a title: without one, screen readers announce an unnamed dialog. To name a dialog without showing the title, wrap the title in VisuallyHidden from reka-ui. The description is optional. When either is missing, the window renders an empty hidden one in its place, so Reka UI does not warn in the console.

KeyAction
Tab / Shift + TabMoves to the next or previous control in the window, wrapping around inside it.
EscapeCloses the dialog and returns focus to the element that opened it. While an input method is composing text, Escape ends the composition instead.

Changelog

  1. registry 0.24.1

    35a5371 — No component styles an element through a :has() on its parent or group any more. Chrome restyles the whole subtree of every :has() anchor above a node that is added or removed, once some rule puts :has() away from the element it styles: a page wrapped in one such anchor recalculated every element for each list row it mounted. The Dialog, Drawer and Tour headers, the InputGroup and InputNumber insets, the Combobox clear button, the InputFloating notch, a FieldLabel beside a disabled checkbox or radio, the Rating ring, and the Slider and ScrollArea examples now read their neighbours with ~ or a :has() on the element itself. The InputGroup addons fade through a variable that the group sets. FileUpload, Image, Marquee and DataTable mark the state on an element instead: the hidden input's focus, an ImageError inside, keyboard focus, and the body above pinned bottom rows. scripts/has-selectors.test.ts keeps the pattern out.

    useSwipeSnap no longer flushes styles for an instant move that leaves the offset where it is, such as new points at rest.

  2. core 0.17.1

    35a5371 — No component styles an element through a :has() on its parent or group any more. Chrome restyles the whole subtree of every :has() anchor above a node that is added or removed, once some rule puts :has() away from the element it styles: a page wrapped in one such anchor recalculated every element for each list row it mounted. The Dialog, Drawer and Tour headers, the InputGroup and InputNumber insets, the Combobox clear button, the InputFloating notch, a FieldLabel beside a disabled checkbox or radio, the Rating ring, and the Slider and ScrollArea examples now read their neighbours with ~ or a :has() on the element itself. The InputGroup addons fade through a variable that the group sets. FileUpload, Image, Marquee and DataTable mark the state on an element instead: the hidden input's focus, an ImageError inside, keyboard focus, and the body above pinned bottom rows. scripts/has-selectors.test.ts keeps the pattern out.

    useSwipeSnap no longer flushes styles for an instant move that leaves the offset where it is, such as new points at rest.

  3. core 0.17.0

    0107e40 — The scrollbar's space is kept only while an overlay locks scrolling, as Base UI does, instead of on every page. @kappa-ui/core/tailwind.css no longer sets html { scrollbar-gutter: stable }, so a page too short to scroll no longer shows an empty strip along its edge on Windows. Dialog, Drawer, Select, Menu, Popover and DatePicker set scrollbar-gutter: stable on <html> while the page is locked and it would otherwise scroll, and remove it afterwards; a gutter your stylesheet already reserves is left alone. Keep ConfigProvider with :scroll-body="false". Want the old always-on gutter? Add html { scrollbar-gutter: stable; } to your stylesheet.

  4. registry 0.22.0

    ca08048 — A Dialog (or AlertDialog, or a useConfirm prompt) opened over a Drawer, or a Drawer opened over a Dialog, dims the page once: the lower overlay turns transparent as it already did for a dialog over a dialog.

    a751cf6 — ScrollArea measures its content in layout pixels, as it measures its viewport: under a scaled ancestor, and in a Dialog, Popover or Menu that opens with the default scale-in, the content was measured short for its whole life, so the thumb came out too long, the end fade dropped out and reachEdge fired early.

    a68b4b7 — Toasts stay clickable while a modal Dialog, Drawer or other overlay that blocks outside pointer events is open: a press on a toast's action runs it instead of falling through to the dialog's overlay and closing the dialog.

  5. registry 0.9.0

    f3e1bd4 — New AlertDialog: shadcn's parts over Reka UI's AlertDialog on Dialog's window and overlay, with AlertDialogMedia, a sm size, and AlertDialogAction / AlertDialogCancel that take Button's variant, color and size. New confirm item: useConfirm() returns confirm, alert and prompt, which open alert dialogs from code and resolve with a DialogResult; onConfirm holds the dialog with a spinner while it runs and keeps it open if it throws, and prompt validates its value.

  6. core 0.8.0

    e60d032 — @kappa-ui/core/dialog exports AlertDialogContent: Reka UI's alert dialog content with the duties of DialogContent, so an alert dialog opened with openDialog reports "escape" and "close-button", holds while loading is on, ignores Escape during IME composition and gets the hidden title and description fallback. DialogContent now shares that code.

  7. registry 0.8.0

    154d2f7 — Drawer: openDrawer and defineDrawer open a drawer from code, and @/ui/drawer re-exports useDialogContext for the component it opens.

    92a9ce3 — Drawer: Drawer, DrawerTrigger, DrawerContent, DrawerOverlay, DrawerHandle, DrawerSwipeArea, DrawerHeader, DrawerTitle, DrawerDescription, DrawerBody, DrawerFooter and DrawerClose over @kappa-ui/core/drawer, shaped like Dialog's parts, on four sides.

  8. core 0.7.0

    92a9ce3 — @kappa-ui/core/drawer: DrawerRoot, DrawerContent, DrawerOverlay, DrawerHandle and DrawerSwipeArea over Reka UI's dialog, with a swipe-to-dismiss gesture on every side, swipe-to-open from the screen edge and a bottom edge that lifts above the virtual keyboard. New modules @kappa-ui/core/drag (useDrag over @use-gesture/vanilla with the drag-start rules) and @kappa-ui/core/virtual-keyboard (useVirtualKeyboardInset). tailwind.css gains drawer-slide and drawer-overlay-fade. @use-gesture/vanilla and @vueuse/core become dependencies. DismissReason gains "swipe".

    154d2f7 — openDrawer(component, props?, options?) and defineDrawer(component, { props, keepMounted, ...options }) in @kappa-ui/core/drawer open a drawer from code through the dialog service, with Drawer's props as options. A dialog manager entry can carry a root component, which DialogHost renders in place of Reka's DialogRoot.