useFocusTrap
Keeps Tab and Shift+Tab inside an element while it is open, and returns focus to where it was on close. Used by ClickAwayEvent and Popper.
Overview
useFocusTrap keeps keyboard focus inside a container, such as a dialog or popover, while it is active. On activation it focuses the container (or its first tabbable child). Tab and Shift+Tab wrap between the first and last tabbable elements. When the trap turns off, focus returns to the element that had it before.
It powers the focusTrap option of ClickAwayEvent and Popper.
Import
import { useFocusTrap } from '@unflowio/ui/hooks/useFocusTrap';Parameters
useFocusTrap(containerRef, { listen, autoFocus });| Param | Type | Default | Description |
|---|---|---|---|
containerRef | RefObject<T | null> | — | Required. The element to trap focus in |
listen | boolean | true | Whether the trap is on. Pass the open state, combined with any option that turns trapping off |
autoFocus | boolean | undefined | Focus the first tabbable child on activation instead of the container |
Return value
None.
Usage
import { useRef } from 'react';
import { useFocusTrap } from '@unflowio/ui/hooks/useFocusTrap';
function ConfirmPopover({ open, onClose }: { open: boolean; onClose: () => void }) {
const ref = useRef<HTMLDivElement>(null);
useFocusTrap(ref, { listen: open, autoFocus: true });
if (!open) {
return null;
}
return (
<div ref={ref} role="dialog" aria-modal="true" aria-label="Delete file" tabIndex={-1}>
<p>Delete this file?</p>
<button onClick={onClose}>Cancel</button>
<button onClick={onClose}>Delete</button>
</div>
);
}Keyboard behavior
| Key | Behavior |
|---|---|
Tab on the last tabbable element | Moves to the first |
Shift+Tab on the first tabbable element | Moves to the last |
Tab / Shift+Tab with focus outside the container | Pulls focus back to the first / last element |
Escape is not handled. Close the container yourself, for example with useClickAway.
Implementation notes
Give the container tabIndex={-1}. Without autoFocus the hook focuses the container itself, which only works if it is focusable.
Only real tab stops count. Elements with tabindex="-1", disabled controls and anything inside [inert] are skipped, so roving-tabindex lists inside the container don't break the wrap.
The container must be mounted when the trap turns on. The hook reads containerRef.current when listen becomes true. Render the container in the same commit (as above), not after an animation delay.
Accessibility
Trap focus only in modal UI, where the rest of the page is out of reach until the user closes it. Give the container a role and an accessible name, and always offer a way out (a close button and Escape). Focus returns to the trigger automatically when the trap ends.