Focus Trap

Utility

Cycles 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-trap

Default

Enable the trap, then press Tab to cycle through the fields.

Preview
Live

Focus trap

tsx
1const inputRef = useRef<HTMLInputElement>(null)
2
3<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.

PropTypeDescription
enabledboolean= trueTurns the trap and initial focus on or off.
initialFocusRefObject<HTMLElement>Element to focus when the trap is enabled.
childrenReact.ReactNodeContent that will hold the focus cycle.
classNamestringOverride the classes of the wrapper div.