DataInterface hooks
useFocusTrap
Keeps keyboard focus inside a container while it is active: focus moves in on open and returns to the element that had it on close, Tab and Shift+Tab wrap, and Escape calls onEscape. With nested traps (a modal opened from a drawer) only the innermost one reacts. Modal and Drawer use it.
import { useFocusTrap } from '@ergasti/bricks';Examples
Trap focus in your own panel
While active, focus moves in, Tab and Shift+Tab wrap, Escape calls onEscape, and focus returns to the button that opened it. Modal and Drawer already do this; use the hook for a custom popover.
Code
import { useRef, useState } from 'react';
import { Button, useFocusTrap } from '@ergasti/bricks';
function Panel() {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useFocusTrap(ref, open, () => setOpen(false));
return (
<div>
<Button onClick={() => setOpen(true)}>Open panel</Button>
{open && (
<div ref={ref} role="dialog" aria-label="Demo panel" style={{ marginTop: 10, padding: 14, borderRadius: 14, background: 'var(--card)', border: '1px solid var(--line)' }}>
<p>Tab stays inside. Escape closes.</p>
<Button size="sm">First</Button> <Button size="sm" onClick={() => setOpen(false)}>Close</Button>
</div>
)}
</div>
);
}Signature
function useFocusTrap(containerRef: RefObject<HTMLElement | null>, active: boolean, onEscape: () => void, options?: FocusTrapOptions): voidParameters
Prop
Type
Returns
void
Related
Button · useDebouncedValue · useIsMobile · useModalLock · useOpenedRow
Source
src/hooks/useFocusTrap.ts (line 111) on GitHub.