Skip to content

Trap Focus

Trap focus within a DOM node.

TrapFocus is a component that manages focus for its descendants. This is useful when implementing overlays such as modal dialogs, which should not allow the focus to escape while open.

When open={true} the trap is enabled, and pressing Tab or Shift+Tab will rotate focus within the inner focusable elements of the component.

⚠️ The component is experimental and unstable.

Example


Disable enforce focus

Clicks within the focus trap behave normally; but clicks outside the focus trap are blocked.

You can disable this behavior with the disableEnforceFocus prop.


Lazy activation

By default, the component moves the focus to its descendants as soon as it opens: open={true}.

You can disable this behavior and make it lazy with the disableAutoFocus prop. When auto focus is disabled, as in the demo below, the component only traps the focus once it gets focused.


Portal

The following demo uses the Portal component to render a subset of the trap focus children into a new "subtree" outside of the current DOM hierarchy, so that they no longer form part of the focus loop.