Playground

useFocusTrap

Keeps Tab focus inside an element while it is active, and returns focus when it closes.

  • Tab and Shift+Tab cycle inside the container while active. Focus moves in on activation.
  • Focus returns to the element that had it before when the trap ends. Escape to close is the caller's job.

Import

import '@monoline/css';
import {useFocusTrap} from '@monoline/react';

Not installed yet? Pick a route.

Copies the source and its styles into your project.

npx monoline add use-focus-trap

Usage

import {useState} from 'react';
import {Button, useFocusTrap} from '@monoline/react';

function TrapDemo() {
  const [open, setOpen] = useState(false);
  const ref = useFocusTrap<HTMLDivElement>(open);
  return (
    <div>
      <Button variant="line" onClick={() => setOpen(true)}>Open trapped panel</Button>
      {open && (
        <div ref={ref} role="dialog" aria-label="Trapped panel">
          <p>Tab stays inside this panel.</p>
          <Button variant="line" onClick={() => setOpen(false)}>Close</Button>
          <Button variant="ghost">Second action</Button>
        </div>
      )}
    </div>
  );
}

<TrapDemo />

Examples

Focus trap

Focus returns to the opening button on close.

Behaviour

  • Tab and Shift+Tab cycle inside the container while active. Focus moves in on activation.
  • Focus returns to the element that had it before when the trap ends. Escape to close is the caller's job.

Keyboard

KeysAction
Tab / Shift+TabCycle inside the container while active
EscapeTo close is the caller's job