use-focus-trap
Usage
use-focus-trap traps focus at given node, for example in modal, drawer or menu. Node must include at least one focusable element. When node unmounts, focus trap is automatically disabled.
API
Hook accepts focus trap active state as single argument:
Hook returns ref
that should be passed to dom node:
Combine with other ref based hooks
Usually focus trap is not used alone. To combine use-focus-trap hook with other ref based hooks use use-merged-ref hook:
Initial focus
By default, focus trap will move focus to first interactive element.
To specify element that should receive initial focus add data-autofocus
attribute,
note that focus trap works with dom and this attribute should be added to element:
Examples
use-focus-trap is used in some Mantine components: Modal, Drawer, Menu and others.
Modal example – when modal is opened focus is trapped inside:
Menu example – when menu is opened focus is trapped inside and Tab key is disabled: