DOMIntermediateSSR-safehooks/dom/useFocusTrap.ts

useFocusTrap

Trap Tab inside a dialog.

Import

TypeScript
import { useFocusTrap } from '@/hooks';

API

Signature

useFocusTrap(ref, active?)

When to use

Use useFocusTrap instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Measurements are 0 / empty until the element is mounted.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useFocusTrap
Editor
function Dialog({ open }: { open: boolean }) {
  const ref = useRef<HTMLDivElement>(null);
  useFocusTrap(ref, open);
  return open ? (
    <div ref={ref} role="dialog">
      <button>One</button>
      <button>Two</button>
    </div>
  ) : null;
}
Preview

Implementation source

Full library source for useFocusTrap — copy into your project when you are not installing a package yet.

hooks/dom/useFocusTrap.ts
import { useEffect } from 'react';
import type { RefObject } from 'react';
import { isBrowser } from '../utility/isBrowser';

const FOCUSABLE =
  'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';

/**
 * Traps Tab focus within a container while active.
 * Restores previously focused element on deactivate.
 */
export function useFocusTrap<T extends HTMLElement>(
  ref: RefObject<T | null>,
  active = true,
): void {
  useEffect(() => {
    if (!isBrowser() || !active) return;
    const container = ref.current;
    if (!container) return;

    const previouslyFocused = document.activeElement as HTMLElement | null;

    const getFocusable = () =>
      Array.from(container.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
        (el) => !el.hasAttribute('disabled') && el.tabIndex !== -1,
      );

    const focusables = getFocusable();
    focusables[0]?.focus();

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key !== 'Tab') return;
      const items = getFocusable();
      if (items.length === 0) {
        event.preventDefault();
        return;
      }
      const first = items[0]!;
      const last = items[items.length - 1]!;
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };

    container.addEventListener('keydown', onKeyDown);
    return () => {
      container.removeEventListener('keydown', onKeyDown);
      previouslyFocused?.focus?.();
    };
  }, [ref, active]);
}

Copy-paste example

useFocusTrap.example.tsx
'use client';

import { useRef } from 'react';
import { useFocusTrap } from '@/hooks';

export function Dialog({ open }: { open: boolean }) {
  const ref = useRef<HTMLDivElement>(null);
  useFocusTrap(ref, open);
  return open ? (
    <div ref={ref} role="dialog">
      <button>One</button>
      <button>Two</button>
    </div>
  ) : null;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Attach the ref before measuring. ResizeObserver requires a mounted element.
  • Source of truth: open hooks/dom/useFocusTrap.ts for implementation details