Focus Trap Beta Focus Trap keeps the focus within its focusable children elements.
install yarn add @clayui/core version use import {FocusTrap } from '@clayui/core' ;
Introduction
Focus Trap is a component that wraps elements in the DOM and prevents focus from escaping from its child components when the user navigates with Tab or Shift + Tab.
It definitely is used when trying to build accessible components, blocking all interactions outside of it while Focus Trap is active.
It’s the responsibility of the user to add an escape method for the focus
trap, either with a button or the escape key.
Example
import {Provider , Button , FocusTrap } from '@clayui/core' ;
import React from 'react' ;
export default function App () {
const [active , setActive ] = React .useState (false );
const activateButtonRef = React .useRef (null );
React .useEffect (() => {
if (active ) {
return () => activateButtonRef .current ?.focus ();
}
}, [active ]);
return (
<Provider spritemap = "/icons.svg" >
<div className = "p-4" >
<Button onClick = {() => setActive (true )} ref = {activateButtonRef }>
Activate trap
</Button >
{active && (
<FocusTrap active = {active }>
<div className = "sheet c-mt-2 c-p-4" >
<Button displayType = "link" >Button 1</Button >
<Button displayType = "link" >Button 2</Button >
<div className = "c-mt-4" >
<Button onClick = {() => setActive (false )}>Leave trap</Button >
</div >
</div >
</FocusTrap >
)}
</div >
</Provider >
);
}Show code API Reference
FocusTrap ({ active , children , focusElementRef }: Props ) => JSX .Element
Parameters Properties Flag to indicate if the focus trap is activated.
children * React .ReactNode
The elements that will receive the focus within the focus trap.
focusElementRef React .RefObject < HTMLElement > | undefined
Ref of the element that receives the focus when the focus trap is activated.
Returns ElementEdit this page on GitHub Contributors
Matuzalém Teles, Veronica Gonzalez
Last edited May 11, 2025 at 5:57:01 PM