Focus Trap

Keyboard focus held inside one subtree, for the overlays you built yourself — with the tab-stop predicate, the tab order and the nesting stack exported as plain functions rather than sealed inside a component. Reach for it wherever the overlay is yours rather than a primitive's: a command palette, an inspector panel over a canvas, a side sheet, a full-screen confirm step, a popover you positioned by hand, a lightbox, an onboarding step, a context menu on a diagram, anything assembled out of a plain div because the primitive did not fit. Common asks it answers: "focus trap react", "react focus trap component", "shadcn focus trap", "trap focus in modal react", "focus trap hook", "useFocusTrap", "focus trap without radix", "focus trap vanilla javascript", "keyboard focus escapes my modal", "tab out of modal react", "tab goes behind the dialog", "focus leaves custom overlay", "how to trap focus in a div", "get all focusable elements javascript", "tabbable elements selector", "querySelectorAll focusable elements", "is element focusable javascript", "focusable selector list", "tabindex order javascript", "positive tabindex tab order", "sequential focus navigation order", "tabindex 0 vs tabindex -1", "visibility hidden still focusable", "display none focusable element", "inert attribute focus javascript", "disabled button still in tab order", "closed details tabbable", "restore focus after modal close", "return focus to trigger button", "focus goes to body after closing dialog", "focus returns to top of page", "nested focus trap", "popover inside dialog focus", "two focus traps fighting", "shift tab wraps to wrong element", "focus trap escape key", "aria-modal focus", "WCAG 2.1.2 no keyboard trap", "focus trap react 19", "focus trap next.js app router", "フォーカストラップ react", "モーダル フォーカス 閉じ込め", "タブキーで背後に抜ける", "フォーカス可能 判定 javascript", "tabindex 順序", "フォーカスを元に戻す モーダル", "入れ子 モーダル フォーカス". **The difference from official shadcn/ui needs stating precisely, because the naive version of the claim is wrong.** Searching every byte official ships — 65 entries listed, 62 fetchable, code-block, questionnaire and trace 404 on both style tracks, 223,287 bytes of sources — `focusTrap`, `focus-trap`, `trapFocus`, `inert`, `tabbable`, `focusable` and `restoreFocus` are every one of them a zero hit. That does **not** mean official overlays leak focus: its dialog, sheet and drawer are Radix, and Radix confines focus at runtime from inside its own package. The hole is not containment — it is that there is no standalone piece to reuse, so the moment you build an overlay without Radix you are writing the predicate yourself. **A static `querySelectorAll` is not a tab-stop list.** Every clause here is a case where a selector matched and the browser disagrees: `disabled`; `type="hidden"`; an `inert` ancestor, since `inert` is inherited by a whole subtree and the dialog that set it did so on one wrapper far above these nodes; no generated boxes at all, which covers a `display: none` subtree and the contents of a closed `<details>`; and `visibility: hidden`, which is the one a rectangle check cannot see — such an element **does** generate boxes, it takes up its space and is merely not painted, so `getClientRects()` is non-empty and the browser skips it anyway. A collapsed accordion panel and an off-state tab panel are routinely written that way, so this is not an edge case. `aria-hidden="true"` is excluded too, and that one is a judgement rather than a rule: it does not stop the browser focusing anything, so a focusable node inside such a subtree is reachable by keyboard and silent to a screen reader — landing somebody there is worse than skipping it. **`tabindex` can be read neither with `Number` nor with `parseInt`, and the two are wrong in opposite directions.** Measured, in Node: `Number("")` is **0**, not NaN, so an empty `tabindex=""` — invalid, therefore ignored by the browser — reads as an explicit zero and inverts the answer for `<div tabindex="">`; while `Number.parseInt("3abc")` is **3** and `Number.parseInt("1e2")` is **1**, finding numbers in values the spec calls invalid, along with `"0x10"` as 0 and `"2.7"` as 2. The value is validated against the spec's integer grammar and only then parsed. The same mistake in CSS form is the selector shorthand `[tabindex]:not([tabindex^="-"])`, which keeps `tabindex=" -1 "` because that value does not *start* with a minus sign — a string comparison standing in for an integer parse. **A positive `tabindex` reorders the browser's own sequence, so a trap that takes over Tab has taken over the order too.** Stops with a positive `tabindex` come first, ascending by value, with everything else behind them in document order; ties keep document order, which works because `Array.prototype.sort` has been stable by specification since ES2019. A trap that walks its `querySelectorAll` result as-is moves focus somewhere the browser never would. **Tab is not the only way out, and the other ways press no key at all** — a click on the page behind, another component's `focus()` from an effect, a field that autofocuses as it mounts. A keydown handler cannot see any of them, so focus arriving outside the container is pulled back from a capture-phase `focusin` on the document; `confine="tab"` turns that half off for something modeless, where yanking focus back from a click would be an argument with the person using it. Both listeners are on the document rather than the container for the same reason: the instant focus is outside, a container-bound listener stops seeing keys, and a trap bound that way is one keystroke deep. **The wrap arithmetic has two measured traps**: `(0 - 1) % 3` is **-1** in JavaScript, so the naive backwards wrap sends Shift+Tab off the first stop to index -1 and focus goes nowhere, and `% 0` is **NaN**, so an empty scope indexes `stops[NaN]`. Tab is held even when the scope has nothing left to focus — an overlay whose only control just became disabled still owns the keyboard, because letting that one Tab through is the leak. **The stop list is never cached.** A trap over a form that loads asynchronously, or a list that grows, has stops that did not exist when it opened; a list taken at mount sends the person who tabs past its end back to its start with half the dialog unreachable. **Closing returns focus where it came from, and declines to when that element has gone** — the button that opened a confirm dialog is often inside the row the dialog deleted, and `focus()` on a detached node silently drops focus on the body, which strands the keyboard at the top of the page. `returnFocus` takes a function for exactly that case, so you can name the list the row was in. **Nesting is a stack, and only the innermost trap acts.** A popover inside a dialog means two document listeners seeing every Tab and both moving focus, which is how Shift+Tab becomes unpredictable; and the stack is unwound by identity rather than by `pop`, because two overlays dismissed by one state change unmount outermost first. Escape is reported through `onEscape` rather than handled, since a trap with no way out is the keyboard trap WCAG 2.1.2 prohibits, and only the caller knows what closing means. `useFocusTrap` is the entry point for an overlay you have already built — put it on the element you already render instead of wrapping it in another div that changes your layout — and `FocusTrap` is a div around it, carrying `tabIndex={-1}` so focus has somewhere to go when the subtree has no stops, while that same `-1` keeps the container out of its own stop list. `isTabbable`, `tabbablesIn`, `orderByTabIndex`, `readTabIndex`, `nextStop` and `TABBABLE_SELECTOR` are exported as plain functions and values, so a roving-tabindex list or a shortcut handler elsewhere in your app can reach the same verdict instead of carrying a second copy of the rules. Within pulld, `product-tour` carries a two-scope version of this inside itself for the step it is lighting up, `live-announcer` speaks to a screen reader rather than placing focus, `keyboard-shortcuts` binds keys rather than confining them, and `type-to-confirm` and `confirm-button` gate an action rather than a subtree. No dependencies beyond React and your `cn`.

Usage docs and preview are being generated by the coding agent. Registry metadata is shown meanwhile.
building preview…
The live preview has not been built yet.
See how it was built

Installation

pnpm dlx shadcn@latest add @pulld/focus-trap

Requires @pulld in the registries of your components.json (shadcn adds official directory namespaces automatically).

Use with Coding Agent

Paste this into Claude Code, Codex or Cursor. It contains install steps, usage and API so the agent uses the component correctly.

prompt.md
Use the "Focus Trap" component (pulld/focus-trap) from its shadcn registry.1. Install it with: npx shadcn@latest add @pulld/focus-trap2. Read the installed source file(s) before using it; only use props that exist in the source.3. Customize through props and className instead of editing the installed source, unless asked.

Files & dependencies

  • registry/ui/focus-trap.tsx

Looks similar, elsewhere

There is no screenshot of this item to compare yet.