@leejaehyeok/use-focus-trap
v0.2.1
Published
포커스 트랩을 구현한 React Hook
Maintainers
Readme
@leejaehyeok/use-focus-trap
A React hook for trapping focus within a specific container module, enhancing accessibility for modals, dialogs, and specific UI elements.
📦 Installation
npm install @leejaehyeok/use-focus-trap🚀 Quick Start
Wrap your container with the containerRef provided by the hook. The focus will automatically cycle among the focusable elements inside the container when navigating via Tab or Shift + Tab.
import React, { useState } from "react";
import { useFocusTrap } from "@leejaehyeok/use-focus-trap";
export default function App() {
const [isOpen, setIsOpen] = useState(false);
const containerRef = useFocusTrap();
return (
<div>
<button onClick={() => setIsOpen(true)}>Open Modal</button>
{isOpen && (
<div ref={containerRef} role="dialog" aria-modal="true" style={{ padding: "24px", border: "1px solid black", marginTop: "16px" }}>
<h2>Focus Trap Modal</h2>
<p>Focus is trapped within this container.</p>
<button data-initial-focus>Action 1</button>
<button>Action 2</button>
{/* Elements that are disabled are automatically skipped */}
<button disabled>Action 3 (Disabled)</button>
<button onClick={() => setIsOpen(false)}>Close Modal</button>
</div>
)}
</div>
);
}Custom Initial Focus
You can set the initial focus target with a CSS selector. If no match is found, the hook falls back to the first focusable element, then the container itself.
const containerRef = useFocusTrap({ initialFocusSelector: "#primary-action" });🧩 API
useFocusTrap(options?)
type FocusTrapOptions = {
initialFocusSelector?: string; // default: "[data-initial-focus]"
};
const containerRef = useFocusTrap(options);Options
initialFocusSelector: CSS selector for the element that should receive initial focus.
Returns
containerRef: Callback ref to attach to the focus-trapped container element.
🧠 Behavior
- Initial Focus: When mounted, focuses the element matched by
initialFocusSelector, then falls back to the first focusable element, then the container. - Restore Focus: When unmounted or ref changes, focus returns to the previously active element.
- Focus Loop: Pressing
Tabon the last focusable element moves focus to the first one. PressingShift + Tabon the first element moves focus to the last one. - Dynamic Elements: Uses
MutationObserverinternally to automatically re-calculate focusable elements whenever children are added/removed or their visibility/disabled status changes.
🔗 Links
📄 License
MIT © leejh1316
