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
import { useRef } from 'react';
import { useFocusTrap } from '@c15t/react';
const CustomCard = ({ children, ref, ...props }) => {
const localRef = useRef(null);
const cardRef = ref || localRef;
useFocusTrap(true, cardRef);
return (
<div
ref={cardRef}
tabIndex={0}
aria-modal={true}
role="dialog"
{...props}
>
{children}
</div>
);
};
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
shouldTrap
becomes 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
shouldTrap
to 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