Back to Mantine

Focus Trap

apps/mantine.dev/src/pages/core/focus-trap.mdx

9.2.11.6 KB
Original Source

import { FocusTrapDemos, ModalDemos } from '@docs/demos'; import { Layout } from '@/layout'; import { MDX_DATA } from '@/mdx';

export default Layout(MDX_DATA.FocusTrap);

Usage

FocusTrap is a component implementation of the use-focus-trap hook. It is used in all Mantine components that require focus trap (Modal, DatePicker, Popover, etc.).

<Demo data={FocusTrapDemos.usage} />

Initial focus

To define the element that will receive initial focus, set the data-autofocus attribute:

<Demo data={FocusTrapDemos.initial} />

FocusTrap.InitialFocus

FocusTrap.InitialFocus is a special component that adds a visually hidden element which will receive the focus when the focus trap is activated. Once FocusTrap.InitialFocus loses focus, it is removed from the tab order.

For example, it is useful if you do not want to focus any elements inside the Modal when it is opened:

<Demo data={ModalDemos.initialFocusTrap} />

Focus trapping logic

  • Focus is trapped within the child node if the active prop is true
  • When the FocusTrap component is mounted or when the active prop changes from false to true, the first element with the data-autofocus attribute is focused
  • If there are no elements with the data-autofocus attribute, then the first element that supports keyboard interaction is focused
  • If the target element does not have focusable elements or does not support ref, then the focus trap will not work
  • Trap stops working when an element outside of the FocusTrap child is focused