Skip to content

useFocusTrap

@astryxdesign/core v0.7.1 · useFocusTrap

Parameters ​

NameTypeDefaultDescription
optionsUseFocusTrapOptions{}Configuration object for the focus trap. Every field inside it is optional.
options.containerRef<HTMLElement | null>—The element that traps focus. Bind the same template ref in the template. Leave it out and the hook creates its own, returned as containerRef.
options.isActiveMaybeRefOrGetter<boolean>—Whether the focus trap is currently active. Turning it on installs the listeners and moves focus in; turning it off removes them and restores focus. isEnabled is the same switch under its other name; either one being true activates the trap.
options.isEnabledMaybeRefOrGetter<boolean>—The same switch as isActive, for callers that read better with it. Pass either name, not both.
options.onEscape() => void—Callback when Escape is pressed inside the trapped container. The trap does not consume the key: a light-dismiss handler beside it still sees the event.
options.initialFocus() => HTMLElement | null—Element to focus when the trap turns on. Return null to fall back to the first focusable element.

Returns ​

NameTypeDescription
containerRefRef<HTMLElement | null>Ref to attach to the container element that should trap focus. It is the ref you passed as container, or the one the hook made for you.
focusFirst() => voidFocuses the first focusable element inside the container.
focusLast() => voidFocuses the last focusable element inside the container.
update() => voidKept for callers that re-measure after the container's children change. It does nothing: the focusable elements are read on each key press.