🔍 What is a Focus Trap (for accessibility)?
A focus trap ensures that when a modal (or dialog) is open, keyboard users (e.g., using the Tab key) can’t move focus outside of it — they stay “trapped” inside the modal until it’s closed.
💡 Why is this important?
For users who:
-
Don’t use a mouse
-
Use screen readers or keyboard navigation
…it’s critical that focus doesn’t move behind or outside a modal, because that breaks the experience and confuses them.
✅ Example without focus trap (bad):
User presses Tab → focus moves to elements behind the modal (e.g., page buttons). That’s confusing and inaccessible.
✅ Example with focus trap (good):
User presses Tab:
-
Focus moves only within modal buttons/inputs
-
Wraps back to first focusable item when reaching the end
🛠️ How to implement it
If you want to do it manually in React, you can:
-
Find all focusable elements inside the modal
-
Use
keydownto trap focus between them
But it's easier to use a library:
npm install focus-trap-react
Then:
import FocusTrap from 'focus-trap-react';
<FocusTrap active={isOpen}>
<div className="modal-content">
{/* Modal content here */}
</div>
</FocusTrap>