use-focus-trap

Trap focus inside given node
Import

Usage

Use use-focus-trap hook to trap focus at given node, for example in modal, drawer or menu. Node must include at least one focusable element. When node unmounts, focus trap automatically disabled.

import { useFocusTrap } from '@mantine/hooks';
function YourModal() {
const focusTrapRef = useFocusTrap();
return (
<div ref={focusTrapRef}>
<input />
</div>
);
}

API

Hook accepts focus trap active state as single argument:

useFocusTrap(); // -> focus trap inactive
useFocusTrap(true); // -> focus trap active
useFocusTrap(false); // -> focus trap disabled

Hook returns ref that should be passed to dom node:

const focusTrapRef = useFocusTrap();
// With regular element:
<div ref={focusTrapRef} />
// With Mantine component:
<Paper elementRef={focusTrapRef} />

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:

import { useRef } from 'react';
import { useClickOutside, useFocusTrap, useMergedRef } from '@mantine/hooks';
function Demo() {
const myRef = useRef();
const useClickOutsideRef = useClickOutside(() => {});
const focusTrapRef = useFocusTrap();
const mergedRef = useMergedRef(myRef, useClickOutsideRef, focusTrapRef);
return <div ref={mergedRef} />;
}

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:

import { useFocusTrap } from '@mantine/hooks';
function YourModal() {
const focusTrapRef = useFocusTrap();
return (
<div ref={focusTrapRef}>
<input />
{/* Second input in modal will have initial focus */}
<input data-autofocus />
<input />
</div>
);
}

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:

Definition

function useFocusTrap(active?: boolean): (instance: HTMLElement) => void;
Build fully functional accessible web applications with ease
Feedback
Your feedback is most valuable contribution to the project, please share how you use Mantine, what features are missing and what is done good
Leave feedback