FocusTrap

Trap focus at child node
Import

Usage

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

import { useDisclosure } from '@mantine/hooks';
import { FocusTrap, TextInput, Button } from '@mantine/core';
function Demo() {
const [active, handlers] = useDisclosure(false);
return (
<div style={{ maxWidth: 400, marginLeft: 'auto', marginRight: 'auto' }}>
<Button onClick={handlers.toggle}>{active ? 'Deactivate' : 'Activate'} focus trap</Button>
<FocusTrap active={active}>
<div>
<TextInput mt="sm" label="First input" placeholder="First input" />
<TextInput mt="sm" label="Second input" placeholder="Second input" />
<TextInput mt="sm" label="Third input" placeholder="Third input" />
</div>
</FocusTrap>
</div>
);
}

Initial focus

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

import { useDisclosure } from '@mantine/hooks';
import { FocusTrap, TextInput, Button } from '@mantine/core';
function Demo() {
const [active, handlers] = useDisclosure(false);
return (
<div style={{ maxWidth: 400, marginLeft: 'auto', marginRight: 'auto' }}>
<Button onClick={handlers.toggle}>{active ? 'Deactivate' : 'Activate'} focus trap</Button>
<FocusTrap active={active}>
<div>
<TextInput mt="sm" label="First input" placeholder="First input" />
<TextInput mt="sm" label="Second input" placeholder="Second input" data-autofocus />
<TextInput mt="sm" label="Third input" placeholder="Third input" />
</div>
</FocusTrap>
</div>
);
}

Focus trapping logic

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

FocusTrap component props

NameTypeDescription
active
boolean
Determines whether focus should be trapped within child element
children *
any
Element at which focus should be trapped, should support ref prop
refProp
string
Prop that should be used to access component ref