Skip to content
GaudiGaudi Design System home

Search documentation

Search every page, heading and paragraph.

useFocusTrap

Keep Tab focus inside a custom overlay and restore it on close.

HooksA11y@gaudi/design-system/hooks/a11y/use-focus-trapView in StorybookSource

While active, Tab and Shift+Tab wrap inside the container. On activation it focuses the first tabbable element (or the container), and on release it returns focus to where it was. Traps nest, and portaled menus inside the trap keep their own focus.

Usage

import { useFocusTrap } from '@gaudi/design-system/hooks';
const trapRef = useFocusTrap({ active: open });
<div ref={trapRef} role='dialog' aria-modal='true' aria-labelledby='menu-title'>…</div>

Examples

Custom reply panel

Storybook

Focus the container first

Storybook

API

5 options
1 return value

Accessibility

A trap must always have a visible, keyboard-reachable way out (a Close button and Escape). Pair it with role="dialog", aria-modal and a label, and with useScrollLock so the page behind does not scroll.

Notes

  • Gaudi Dialog, Dialog confirmation, Sheet and Drawer already trap focus; use this hook only for custom overlays.