useFocusTrap@astryxdesign/core v0.5.2 · useFocusTrap

Usage

Traps focus within a container element following the WAI-ARIA dialog focus trap pattern. Listens to focus events on the document and redirects focus back into the container if it escapes via keyboard navigation. Handles both Tab and Shift+Tab wrapping. When the trap deactivates or unmounts, focus is restored to the element that was focused before activation, unless focus was already moved elsewhere. Mouse clicks outside the container are not intercepted; use a light-dismiss handler for that.

ts
import {useFocusTrap} from '@astryxdesign/core/hooks'

Best practices

GuidancePractices
Do

Call focusFirst() when opening a dialog/modal to move focus into the trapped region.

Do

Provide an onEscape callback to close the dialog when Escape is pressed.

Do

Rely on the built-in focus restoration on close; only add your own onHide focus handling when you need to send focus somewhere other than the previously-focused element.

Don't

Use on non-modal content like tooltips or dropdowns; those need light-dismiss, not focus trapping.

Parameters

ParamTypeDescription
optionsrequired

Configuration object for the focus trap.

options.isActiverequired
boolean

Whether the focus trap is currently active.

options.onEscape
() => void

Callback when Escape key is pressed inside the trapped container.

Returns

FieldTypeDescription
containerRefReact.RefObject<HTMLElement | null>

Ref to attach to the container element that should trap focus.

focusFirst() => void

Focuses the first focusable element inside the container.