Trap Focus

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

Usage

custom-modal.tsx
import {
Modal,
Button,
trapFocus,
useModal
} from '@cerberus/react'
function SomePage() {
const { modalRef, show, close } = useModal()
const handleKeyDown = trapFocus(modalRef)
return (
<div>
<Button onClick={show}>Show Modal</Button>
<Modal onKeyDown={handleKeyDown} ref={modalRef}>
This is a custom modal!
<Button onClick={close}>
Close
</Button>
</Modal>
</div>
)
}

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