Focus Trap
UtilityCycles keyboard focus within a container.
FocusTrap keeps Tab and Shift+Tab inside its children, wrapping focus at the edges. It can focus a specific element on enable via initialFocus.
npx shadcn@latest add focus-trapDefault
Enable the trap, then press Tab to cycle through the fields.
Preview
LiveFocus trap
tsx
1const inputRef = useRef<HTMLInputElement>(null)23<FocusTrap enabled={enabled} initialFocus={inputRef} className="rounded-lg border p-4">4 <Input ref={inputRef} placeholder="Name" />5 <Input placeholder="Email" />6 <Button>Save</Button>7</FocusTrap>
API reference
All props of the underlying Base UI primitive are forwarded. The table below documents the Shelf-specific props.
| Prop | Type | Description |
|---|---|---|
| enabled | boolean= true | Turns the trap and initial focus on or off. |
| initialFocus | RefObject<HTMLElement> | Element to focus when the trap is enabled. |
| children | React.ReactNode | Content that will hold the focus cycle. |
| className | string | Override the classes of the wrapper div. |