A hook to trap focus within a container element for accessibility.
Made by raouf.codesOverview
The useFocusTrap hook traps focus within a container element, ensuring that Tab and Shift+Tab navigation cycles through focusable elements without escaping. This is essential for accessible modals, dialogs, and dropdown menus.
Installation
Usage
Basic
With Multiple Focusable Elements
API Reference
useFocusTrap
| Prop | Type | Default |
|---|---|---|
active | boolean | - |
containerRef | React.RefObject<HTMLElement | null> | - |
Focusable Elements
The hook considers the following elements as focusable:
a[href]— Links with href attributebutton:not([disabled])— Enabled buttonstextarea:not([disabled])— Enabled textareasinput:not([disabled])— Enabled inputsselect:not([disabled])— Enabled selects[tabindex]:not([tabindex="-1"])— Elements with positive tabindex
Features
- Automatic focus — Focuses the first focusable element when trap activates
- Circular navigation — Tab from last element wraps to first, Shift+Tab from first wraps to last
- Conditional activation — Only traps focus when
activeis true - Clean cleanup — Removes event listeners when deactivated
Accessibility
Focus trapping is crucial for:
- Modals/Dialogs — Prevents users from accidentally interacting with content behind the modal
- Dropdown menus — Keeps focus within the menu until closed
- Popovers — Ensures keyboard users can navigate within the popover
Credits
- Based on ARIA Authoring Practices for modal dialogs
Built by raouf.codes. The source code is available on GitHub.
Last updated: 2/27/2026