useFocusTrap
Keeps Tab focus inside an element while it is active, and returns focus when it closes.
Source@monoline/react 0.5.0Markdown for AI toolsstable
- Tab and Shift+Tab cycle inside the container while active. Focus moves in on activation.
- Focus returns to the element that had it before when the trap ends. Escape to close is the caller's job.
Import
import '@monoline/css';
import {useFocusTrap} from '@monoline/react';
Not installed yet? Pick a route.
Copies the source and its styles into your project.
npx monoline add use-focus-trap
Usage
import {useState} from 'react';
import {Button, useFocusTrap} from '@monoline/react';
function TrapDemo() {
const [open, setOpen] = useState(false);
const ref = useFocusTrap<HTMLDivElement>(open);
return (
<div>
<Button variant="line" onClick={() => setOpen(true)}>Open trapped panel</Button>
{open && (
<div ref={ref} role="dialog" aria-label="Trapped panel">
<p>Tab stays inside this panel.</p>
<Button variant="line" onClick={() => setOpen(false)}>Close</Button>
<Button variant="ghost">Second action</Button>
</div>
)}
</div>
);
}
<TrapDemo />
Examples
Behaviour
- Tab and Shift+Tab cycle inside the container while active. Focus moves in on activation.
- Focus returns to the element that had it before when the trap ends. Escape to close is the caller's job.
Keyboard
| Keys | Action |
|---|---|
| Tab / Shift+Tab | Cycle inside the container while active |
| Escape | To close is the caller's job |