useFocusTrap
The useFocusTrap hook provides accessibility-focused keyboard navigation management, keeping focus trapped within modal components for better user experience.
The useFocusTrap hook creates an accessible experience by preventing keyboard focus from leaving a specific container element (like a dialog or modal) until it's dismissed. This is essential for users navigating with keyboards or screen readers.
Usage
How It Works
When activated, the useFocusTrap hook:
- Stores the element that was focused before trapping began
- Finds all focusable elements within the container
- Sets initial focus to the first focusable element (or the container itself)
- Captures Tab and Shift+Tab keystrokes to cycle focus within the container
- Restores focus to the original element when the component unmounts or
shouldTrapbecomes false
Notes
- Hook must be called with a valid element reference that contains focusable elements
- Adding
tabIndex={0}to the container ensures it can receive focus if no focusable children exist - Always include proper ARIA attributes (
role="dialog"andaria-modal="true") for screen reader accessibility - The hook automatically restores focus to the previously focused element when the component unmounts
- Set
shouldTrapto false when you want to disable focus trapping temporarily
Accessibility Compliance
Using this hook helps your application comply with these WCAG 2.1 requirements:
- 2.1.2: No Keyboard Trap - While this criterion warns against trapping keyboard focus, modal dialogs are an exception when implemented properly
- 2.4.3: Focus Order - Ensures focus moves in a meaningful sequence