useFocusTrap
Traps keyboard focus inside the given container while active is true. Cycles Tab / Shift+Tab between the first and last focusable descendants. On activation, focus moves to initialFocus (or the first focusable child). On deactivation, focus returns to whatever was focused before, unless returnFocus is false.
Used internally by Modal and Drawer to keep keyboard navigation inside the dialog.
import { useRef, useState } from 'react'
import { useFocusTrap, useScrollLock } from '@wire-ui/react'
function Dialog() {
const [open, setOpen] = useState(false)
const dialogRef = useRef<HTMLDivElement>(null)
useFocusTrap(dialogRef, { active: open })
useScrollLock(open)
return (
<>
<button onClick={() => setOpen(true)}>Open dialog</button>
{open && (
<div ref={dialogRef} role="dialog" aria-modal="true">
<input placeholder="First field" />
<input placeholder="Second field" />
<button onClick={() => setOpen(false)}>Close</button>
</div>
)}
</>
)
}Parameters
| Param | Type | Description |
|---|---|---|
containerRef | RefObject<HTMLElement | null> | Element to trap focus inside. |
options | UseFocusTrapOptions | See below. |
Options
| Option | Type | Default | Description |
|---|---|---|---|
active | boolean | true | Whether the trap is active. |
returnFocus | boolean | true | Restore focus to the previously focused element on deactivate. |
initialFocus | RefObject<HTMLElement | null> | HTMLElement | null | First focusable child | Element to focus when the trap activates. |
Last updated on