Hooks
/ API Reference
Hooks
/ API Reference

useFocusTrap

A hook that traps focus within a given element.
This is useful for components like modals or popovers.

Tip

Use active if your component is hidden via CSS display, but always mounted. Otherwise the focus will be trapped in whatever component is rendered last.

The Gist

'use client'
import { useFocusTrap } from '@weser/hooks'

function Component() {
  const ref = useRef<HTMLDivElement>(null)

  useFocusTrap(ref)

  return (
    <div ref={ref}>
      <button>Button 1</button>
      <button>Button 2</button>
      <button>Button 3</button>
    </div>
  )
}

Parameters

ParameterTypeDefaultDescription
refRefObject (new tab)The ref object to use.
activeboolean?trueWhether the hook is active.
On this page