ComponentformZero dependencies

Focus Trap

Pure TypeScript focus trapping helpers for accessible overlays: getFocusable and trapFocus.

Preview

Live Preview
Open ↗

Installation

Tokens guide →

Add to your project via CLI (zero dependencies, code you own):

npx bigbullui add focus-trap

Or install the full npm package:

npm install bigbullui

Usage

tsx3 lines
import { trapFocus } from "@/components/ui/lib/focus-trap"; onKeyDown={(e) => { if (e.key === "Tab") trapFocus(containerRef.current, e.nativeEvent); }}

Source code

lib/focus-trap.ts

Zero third-party dependencies (only React + standard DOM APIs). Copy directly into your project:

tslib/focus-trap.ts193 lines
export function getFocusable(container: HTMLElement): HTMLElement[] {  const focusableSelector = [    "a[href]",    "area[href]",    'input:not([disabled]):not([type="hidden"])',    "select:not([disabled])",    "textarea:not([disabled])",    "button:not([disabled])",    "details > summary",    "audio[controls]",    "video[controls]",    '[tabindex]:not([tabindex="-1"])',    '[contenteditable="true"]',    '[contenteditable=""]',    "object[data]",    "embed",    "iframe",  ].join(",");

Props

PropTypeDescription
containerHTMLElementTrap boundary element (trapFocus arg, required).
eventKeyboardEventNative Tab key event (trapFocus arg, required).