useFocusTrap

Trap keyboard focus within a container for accessible modal dialogs.

useFocusTrap() keeps keyboard focus within a container element while active. This is essential for accessibility - when a modal dialog is open, Tab and Shift+Tab should cycle through focusable elements inside the dialog, not escape to the page behind it.

Parameters

ParameterTypeDescription
shouldTrapbooleanWhether focus should be trapped
containerRefRefObject<HTMLElement | null> | nullRef to the container element

Behavior

  • Tab: Moves focus to the next focusable element. Wraps to the first element when reaching the end.
  • Shift+Tab: Moves focus to the previous focusable element. Wraps to the last element when reaching the start.
  • Focus is restored to the previously focused element when the trap is deactivated.

Info

ConsentBanner and ConsentDialog use useFocusTrap internally when trapFocus is enabled (default: true). You only need this hook when building custom consent UI.