solid-focus-trap
TypeScript icon, indicating that this package has built-in type declarations

0.1.7 • Public • Published

SolidJS utility that traps focus inside a given DOM element.

Features

  • Watches for DOM changes inside the focus trap and updates accordingly
  • Properly restores focus when the trap gets disabled
  • Very customizable

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, // default = true
    observeChanges: true, // default
    restoreFocus: true, // default
  })

  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

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>
  )
}

Further Reading

This utility is from the maintainers of corvu, a collection of unstyled, accessible and customizable UI primitives for SolidJS. It is also documented in the corvu docs under Focus Trap.

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
0.1.72,400latest

Version History

VersionDownloads (Last 7 Days)Published
0.1.72,400
0.1.638
0.1.50
0.1.40
0.1.30
0.1.20
0.1.10
0.1.00

Package Sidebar

Install

npm i solid-focus-trap

Weekly Downloads

2,064

Version

0.1.7

License

MIT

Unpacked Size

17.7 kB

Total Files

6

Last publish

Collaborators

  • giyomoon