Skip to main content

Focus Trap

The focus trap utility is used to trap focus within a DOM element, preventing users from tabbing outside of a specific region.

Features

  • Handles edge cases like hidden elements
  • Works with shadow DOM
  • Supports nested focus traps
  • Follows ARIA-controlled elements

Installation

npm install @zag-js/focus-trap

Usage

import { trapFocus } from "@zag-js/focus-trap" // Trap focus within an element const restore = trapFocus(element, { initialFocus: "#first-input", returnFocusOnDeactivate: true, }) // Later, release the trap restore()

Framework Usage

import { useEffect, useRef } from "react" import { trapFocus } from "@zag-js/focus-trap" export function Dialog() { const ref = useRef<HTMLDivElement | null>(null) useEffect(() => { if (!ref.current) return return trapFocus(ref.current, { initialFocus: "[data-autofocus]", }) }, []) return ( <div ref={ref}> <button data-autofocus>Close</button> <input type="text" placeholder="Enter text..." /> <button>Submit</button> </div> ) }

API Reference

trapFocus

function trapFocus( element: HTMLElement | null | (() => HTMLElement | null), options?: TrapFocusOptions, ): () => void

Creates a focus trap for the specified element.

Parameters:

  • element - The container element to trap focus within, or a function that returns the element
  • options - Configuration options for the focus trap

Returns: A cleanup function that deactivates the focus trap when called.

Options

PropertyDescription
initialFocusElement to receive focus on activation
fallbackFocusFallback element if no tabbable elements found
returnFocusOnDeactivateReturn focus to previous element on deactivation
escapeDeactivatesAllow ESC key to deactivate trap
clickOutsideDeactivatesDeactivate trap on outside click
allowOutsideClickAllow outside clicks without deactivating
preventScrollPrevent scrolling when focusing
delayInitialFocusDelay initial focus to prevent event capture
followControlledElementsInclude ARIA-controlled elements
getShadowRootEnable shadow DOM traversal
isKeyForwardCustom forward navigation key
isKeyBackwardCustom backward navigation key
onActivateCalled before activation
onPostActivateCalled after activation
onDeactivateCalled before deactivation
onPostDeactivateCalled after deactivation
Edit this page on GitHub