useTrapFocus
useTrapFocus
allows you to trap focus inside a specific DOM element. Focus traps are especially useful for modals, dropdown menus, and other elements that should keep focus within the element when it is open.
This is a great way to improve the accessibility of your application because with focus traps, you can ensure that users navigating your site using only a keyboard won't accidentally interact with elements outside the focus trap.
Under the hood, useTrapFocus
uses focus-trap/tabbable
. To learn more about their specific implementation and see the rules used to gather focusable elements visit the tabbable docs.
Usage
Base Usage
To use useTrapFocus
, we can use React.ref
to identify the element that we want to trap focus inside of. Then, we can pass that ref to useTrapFocus
and whenever that element is being rendered, the focus trap will be active.
import * as React from 'react';
import { useTrapFocus } from '@storefront-ui/react';
function CustomTooltip(props: Props) {
const focusTrapElementRef = React.useRef(null);
useTrapFocus(focusTrapElementRef);
return (
<div ref={focusTrapElementRef}>
This container has <a href="#">Focusable anchor</a> and another <button>Focusable button</button> or <span className="focus:outline" tabindex="0">Focusable span</span>
</div>
);
}