useFocusTrap

Traps focus within a specified element.

Examples

In these examples, clicking outside of an active focus trap will disable the focus trap. This is not the default behavior. It's just a workaround so focus behavior is not broken on the page if a user forgets to disable the focus trap after interacting with the example.

Default

Could not load examples for Primer component library: product

Custom first focused element

Could not load examples for Primer component library: product

Return focus to the previously focused element after focus trap is turned off

Press the Escape key while focused in the trap to toggle the focus trap off.

When the focus trap is turned off, focus will return to the element focused before entering the focus trap.

Could not load examples for Primer component library: product

Return focus to a specific element after focus trap is turned off

Press the Escape key while focused in the trap to toggle the focus trap off.

When the focus trap is turned off, focus will always return to the same element.

Could not load examples for Primer component library: product

API

Loading data for useFocusTrap...