shadcn/ui Dialog focus trap and auto-focus fixes
Stop shadcn/ui Dialog from auto-focusing the close button or mobile keyboard, fix focus return from DropdownMenu, and handle third-party portals.
- shadcn 4.23.0
- Tailwind CSS 4.3.5
- Vite 8
- React 19.3
shadcn/ui Dialog traps keyboard focus and automatically focuses the first tabbable element when it opens. That is great for accessibility, until it auto-focuses the Close X button with a bright focus ring, opens the mobile keyboard on an input you didn't want focused, or blocks clicks on a third-party date picker or Stripe element.
Three common focus issues and exact fixes
Step 1: Stop the Dialog from auto-focusing the first input or close button
Use
onOpenAutoFocus={(e) => e.preventDefault()}onDialogContent, or move focus explicitly to a heading or primary field:dialog-autofocus.tsxTSX <DialogContent onOpenAutoFocus={(e) => e.preventDefault()}> <DialogHeader> <DialogTitle>Confirm delete</DialogTitle> </DialogHeader></DialogContent>Step 2: Control where focus returns on close
When a dialog opens from a
DropdownMenuItem, closing the dialog tries to return focus to the now-unmounted menu item, jumping focus back to<body>. UseonCloseAutoFocusto focus the dropdown trigger button instead:dialog-close-focus.tsxTSX <DialogContent onCloseAutoFocus={(e) => { e.preventDefault(); triggerRef.current?.focus(); }}>Step 3: Third-party portals (Stripe, Google Places, TinyMCE) can't be focused
Radix's modal focus trap pulls focus back inside
DialogContentwhenever a click lands on a portal appended directly to<body>. Either mount the third-party popover inside the dialog container, or passmodal={false}on<Dialog modal={false}>if you render your own backdrop.
Questions
Why can't I scroll a Combobox inside a Dialog?
That is a related Radix scroll-lock + focus-trap conflict. Set modal={true} on the inner Popover; see shadcn/ui Combobox not scrolling inside a Dialog.
Is disabling onOpenAutoFocus bad for accessibility?
Only if keyboard users lose track of where they are. If you prevent auto-focus on an input, keep the dialog itself focusable (tabIndex={-1}) or move focus to the dialog's primary action so screen readers still announce the modal.
Related articles
- shadcn/uishadcn/ui Combobox not scrolling inside a DialogFix a shadcn/ui Combobox or Popover inside a Dialog: set modal={true} on Popover, stop wheel propagation on CommandList, and fix focus trapping.
- shadcn/uishadcn/ui Base UI vs Radix: which primitive library to pickCompare Radix UI (asChild, data-state) and Base UI (render prop, data-open) in shadcn/ui: composition, Tailwind v4 animations, registries, and when to pick each.
- shadcn/uishadcn/ui animations not working on Tailwind v4Dialogs and accordions without animation mean a missing tw-animate-css or shadcn/tailwind.css import. Why the second one fails silently, and how to check.
Still stuck? We answer every message ourselves. Write to us