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
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
Full Signature
initialFocus?union
Element, ref, or CSS selector to focus when the trap activates
Full Signature
restoreFocus?uniondefault:true
Restore focus to the previously active element on cleanup
Full Signature
onEscape?function
Callback fired when the
Escape key is pressed while the trap is activeFull Signature
Parameters
(eventKeyboardEvent