Skip to the content

useFocusTrap

useFocusTrap keeps keyboard focus inside a modal surface. While active it moves focus into the container, wraps Tab and Shift+Tab at the edges, calls onEscape on Escape, and returns focus to the previous element on release. Modal and Sheet use it. It adds no nodes to the DOM.
Hooks

Signature

useFocusTrap(ref: React.RefObject<HTMLElement | null>, opt: { active: boolean; onEscape?: () => void }): void;
Name
Type
Description
ref
RefObject<HTMLElement>
The container. Give it tabIndex={-1} so it can take focus when it has no controls.
opt.active
boolean
Engages the trap; false releases it and restores focus.
opt.onEscape
() => void
Called on Escape. The event is stopped so outer layers do not react too.
returns
void
Scrolls sideways inside the table. The page does not.

Example

function Dialog({ open, onClose, children }) {
  const panelRef = useRef<HTMLDivElement>(null);
  useFocusTrap(panelRef, { active: open, onEscape: onClose });

  if (!open) return null;
  return (
    <div ref={panelRef} role="dialog" aria-modal="true" tabIndex={-1}>
      {children}
    </div>
  );
}

Pitfalls

  • Engaging the trap before the container is in the DOM traps nothing. With useExitTransition, gate active on open && mounted.
  • Focusable means links with href, enabled form controls and elements with a non-negative tabindex; hidden elements are skipped. Custom widgets need a tabindex.
  • Use it only for modal surfaces. Menus, tooltips and popovers must let focus leave.

See also