use-focus-trap
Trap focus inside given node
Import
Source
Docs
Package
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 React from 'react';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 inactiveuseFocusTrap(true); // -> focus trap activeuseFocusTrap(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 React, { 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 React from 'react';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, TagPicker and others.
Modal example – when modal is opened focus is trapped inside:Definition
function useFocusTrap(active?: boolean): (instance: HTMLElement) => void;