focus-trap-react demo

Return to the repository


Default behavior: When this FocusTrap mounts (and activates), the first element in its tab order receives focus.

first focus, no escape

When this FocusTrap mounts (and activates), focus jumps to a specific, manually specified element.

Also, the Escape key does not deactivate this trap; you have to click the button to deactivate.

special element

Inspect this element and you'll see that it is not the default plain div, but rather a section tag with an id, a class, inline styles, and an arbitrary data-attribute.

Also, this FocusTrap activates and deactivates while staying mounted.

ALSO, when you click outside this FocusTrap, the trap deactivates and your click carries through.

Finally, focus should return to the "activate trap" button, whether you click the "deactivate trap" button, or press the ESC key.

demo autofocus

The trap contains an input with the autofocus attribute.

demo containerElements

You may pass in an array prop containerElements that contains nodes to trap focus within, which if passed will be used instead of the direct child. The direct child, if any, will be ignored by the trap (unless also given as an element in containerElements).

demo containerElements (no child)

Slight underlying difference from the previous "containerElements" demo in that the focus trap element is not given a child: <FocusTrap containerElements={[...]} />. The result is the same, but this further reinforces the fact that when containerElements is used, the child is not considered, and therefore not even necessary.

Return to the repository