Skip to Content
ohooks

useFocusTrap

Traps keyboard Tab / Shift+Tab focus within a container element and optionally restores focus on unmount.

Loading preview...

The useFocusTrap hook constrains keyboard Tab and Shift+Tab navigation to focusable elements inside a container, moves initial focus into the container when activated, and restores focus to the previously focused element when deactivated.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useFocusTrap.json

Usage

Examples

Accessible Modal Dialog

Combine enabled, initialFocus, and onEscape to trap focus inside an open modal and close it when the user presses Escape.

Custom Initial Focus Element

Pass a RefObject or CSS selector to initialFocus to control which element receives focus when the trap activates.

API Reference

UseFocusTrapOptions

Configuration options for focus trapping, initial focus target, and restoration behavior.

Property
Specification
enabled?
uniondefault:true
Whether the focus trap is currently active
initialFocus?
union
Element, ref, or CSS selector to focus when the trap activates
restoreFocus?
uniondefault:true
Restore focus to the previously active element on cleanup
onEscape?
function
Callback fired when the Escape key is pressed while the trap is active