@ryvora/react-focus-scope
v2.0.0
Published
🎯 Trap and manage focus within a section of your app. Essential for modals and dialogs!
Maintainers
Readme
Focus Scope 🎯
Greetings, Focus Commander! 🎖️
The focus-scope module is a powerful tool for managing focus within a specific section of your application. It's essential for creating accessible modals, dialogs, and other UI elements that need to "trap" focus temporarily.
It's like creating a VIP lounge for keyboard focus – once you're in, you can't easily leave until the party's over! 🥳
Key Powers
- 🔒 Focus Trapping: Keeps the Tab key (and Shift+Tab) cycling within the scope.
- 🚀 Auto Focus on Mount: Can automatically focus on a specific element when the scope mounts.
- 🧐 Restore Focus on Unmount: Remembers what was focused before the scope became active and restores focus to it when the scope unmounts.
- 💂 Uses Focus Guards: Often utilizes
focus-guardsinternally for robust trapping.
Basic Usage
import { FocusScope } from '@ryvora/react-focus-scope';
import React, { useState } from 'react';
function MyModal() {
const [isOpen, setIsOpen] = useState(false);
const triggerRef = React.useRef<HTMLButtonElement>(null);
if (!isOpen) {
return (
<button ref={triggerRef} onClick={() => setIsOpen(true)}>
Open Modal
</button>
);
}
return (
<FocusScope
trapped
onMountAutoFocus={(e) => e.preventDefault()}
onUnmountAutoFocus={() => triggerRef.current?.focus()}
>
<div role="dialog" aria-modal="true">
<p>I am a modal! Focus is trapped here.</p>
<input type="text" placeholder="Try tabbing" />
<button onClick={() => setIsOpen(false)}>Close</button>
</div>
</FocusScope>
);
}Stay focused and build accessible UIs! 🌟
