SolidJS utility that traps focus inside a given DOM element.
npm install solid-focus-trapSolidJS utility that traps focus inside a given DOM element.
- Watches for DOM changes inside the focus trap and updates accordingly
- Properly restores focus when the trap gets disabled
- Very customizable
``tsx`
import createFocusTrap from 'solid-focus-trap'
`tsx
const DialogContent: Component<{
open: boolean
}> = (props) => {
const [contentRef, setContentRef] = createSignal
createFocusTrap({
element: contentRef,
enabled: () => props.open, // default = true
observeChanges: true, // default
restoreFocus: true, // default
})
return (
Dialog
)
}
`
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.
`tsx
const DialogContent: Component<{
open: boolean
}> = (props) => {
const [contentRef, setContentRef] = createSignal
const [initialFocusRef, setInitialFocusRef] =
createSignal
createFocusTrap({
element: contentRef,
enabled: () => props.open,
initialFocusElement: initialFocusRef,
})
return (
Dialog
)
}
``