Back to elements
ElementMiscFree

Focus Trap React component

Keeps keyboard focus inside a dialog, drawer or menu while it's open: Tab and Shift+Tab loop through its controls, focus starts where you choose and returns to where it was, Escape calls you back, and an optional ring glides to whatever has focus.

When to use the Focus Trap component

Use Focus Trap inside anything modal that you build yourself: dialogs, drawers, full-screen menus, command palettes, onboarding overlays. Keyboard and screen reader users otherwise tab into the page hidden behind.

Always give people a way out (Escape and a close button) and let focus return to the control that opened the layer.

Installation

Add the Focus Trap component to your project with the shadcn CLI. It lands in components/focus-trap.tsx as plain React + Tailwind CSS source you own and can edit.

Install
Copied!
npx shadcn@latest add https://reactframe.com/r/focus-trap.json

Or copy the source by hand and install its dependencies:

Install
Copied!
npm install motion clsx tailwind-merge

Props

<FocusTrap /> accepts 4 props, all optional.

  • children
    React.ReactNode
  • showIndicator

    A ring that glides to whichever element has keyboard focus inside the trap.

    boolean
    Default: true
  • indicatorColor
    string
    Default: "#F5F4F1"
  • className
    string

FAQ

What gets focused first?
The element matching initialFocus, otherwise the first focusable element inside, otherwise the container itself.
Where does focus go when it closes?
Back to whatever had focus when the trap turned on, usually the button that opened it. Set returnFocus={false} to handle that yourself.
What is the moving ring?
An optional indicator that glides to the keyboard-focused control, making focus easy to follow. It only shows for keyboard focus and can be turned off with showIndicator={false}.

More Misc components

Icon Swap Toggle
Free
Animate on Scroll
Free
Ripple Click Effect
Free
Speed Dial
Free
Toggle Price Counter
Free
Payment Button
Free