Focus Trap
Utility that traps focus inside a given DOM element.
Features Section titled Features
- Watches for DOM changes inside the focus trap and updates accordingly
- Properly restores focus when the trap gets disabled
- Very customizable
Installation Section titled Installation
npm install solid-focus-trap
Usage Section titled Usage
import createFocusTrap from 'solid-focus-trap'
const DialogContent: Component<{
open: boolean
}> = (props) => {
const [contentRef, setContentRef] = createSignal<HTMLElement | null>(null)
createFocusTrap({
element: contentRef,
enabled: () => props.open
})
return (
<Show when={props.open()}>
<div ref={setContentRef}>Dialog</div>
</Show>
)
}
The first focusable element within the focus trap element will be focused initially. When the trap is disabled, the focus will be restored to the element that was focused before the trap was enabled.
Custom initial focus element Section titled Custom initial focus element
This example shows how to customize the initial focus element so that the focus moves to a specific element when the trap gets enabled.
const DialogContent: Component<{
open: boolean
}> = (props) => {
const [contentRef, setContentRef] = createSignal<HTMLElement | null>(null)
const [initialFocusRef, setInitialFocusRef] =
createSignal<HTMLElement | null>(null)
createFocusTrap({
element: contentRef,
enabled: () => props.open,
initialFocusElement: initialFocusRef,
})
return (
<Show when={props.open()}>
<div ref={setContentRef}>Dialog</div>
<button>Close</button>
<input ref={setInitialFocusRef} />
</Show>
)
}
API reference Section titled API reference
Props
Property | Default | Type/Description |
---|---|---|
element | - | MaybeAccessor<null | HTMLElement> Element to trap focus in. |
enabled | true | MaybeAccessor<boolean> If the focus trap is enabled. |
observeChanges | true | MaybeAccessor<boolean> Whether to watch for changes being made to the DOM tree inside the focus trap and reload the focus trap accordingly. |
initialFocusElement | The first focusable element inside element | MaybeAccessor<null | HTMLElement> The element to receive focus when the focus trap is activated. |
onInitialFocus | - | (event: Event) => void Callback fired when focus moves inside the focus trap. Can be prevented by calling event.preventDefault . |
restoreFocus | true | MaybeAccessor<boolean> If the focus should be restored to the element the focus was on initially when the focus trap is deactivated. |
finalFocusElement | The element the focus was on initially | MaybeAccessor<null | HTMLElement> The element to receive focus when the focus trap is deactivated ( enabled = false ). |
onFinalFocus | - | (event: Event) => void Callback fired when focus moves outside the focus trap. Can be prevented by calling event.preventDefault . |
Developed and designed by Jasmin