Trap Focus

The trapFocus helper allows you to trap the focus within a Modal.

When to use

This helper is ideal for when you are using a custom Modal.

Usage

custom-modal.tsx
1
import {
2
Modal,
3
Button,
4
trapFocus,
5
useModal
6
} from '@cerberus-design/react'
7
8
function SomePage() {
9
const { modalRef, show, close } = useModal()
10
const handleKeyDown = trapFocus(modalRef)
11
12
return (
13
<div>
14
<Button onClick={show}>Show Modal</Button>
15
16
<Modal onKeyDown={handleKeyDown} ref={modalRef}>
17
This is a custom modal!
18
<Button onClick={close}>
19
Close
20
</Button>
21
</Modal>
22
</div>
23
)
24
}

API

define function useModal(modalRef: RefObject<HTMLDialogElement>): KeyboardEventHandler<HTMLDialogElement>

Arguments

The trapFocus helper accepts a single argument:

NameDefaultDescription
refnullThe ref of the dialog element to trap focus within.

On this page