useFocusTrap
Hooks

useFocusTrap

Keeps Tab inside a container, with initial focus and restore on close.

Signature

Cycles Tab and Shift+Tab through the focusable elements inside containerRef. It also moves focus into the container on open and returns focus to the previously focused element on close.

SignatureTypeScript
function useFocusTrap(options: {
  enabled: boolean;
  containerRef: { current: HTMLElement | null };
  /** Element to focus on open. Defaults to the first focusable child. */
  initialFocusRef?: { current: HTMLElement | null };
  /** Set false to trap Tab without moving focus on open. */
  autoFocus?: boolean;
  /** Return focus to the previously focused element on close. */
  restoreFocus?: boolean;
}): void;

Usage

ExampleTSX
import { useRef } from "react";
import { useFocusTrap } from "@solarius/onset";

function Dialog({ open }: { open: boolean }) {
  const containerRef = useRef<HTMLDivElement>(null);
  const confirmRef = useRef<HTMLButtonElement>(null);

  useFocusTrap({
    enabled: open,
    containerRef,
    initialFocusRef: confirmRef,
    restoreFocus: true,
  });

  if (!open) return null;

  return (
    <div
      ref={containerRef}
      role="dialog"
      aria-modal="true"
      aria-label="Confirmation"
    >
      <button ref={confirmRef}>Confirm</button>
    </div>
  );
}