Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 19x 19x 1x 1x 1x 1x 1x 1x | import { useEffect } from "react";
export const useFocusTrap = (
containerRef: React.RefObject<HTMLElement | null>
): void => {
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
const containerElement = containerRef.current;
const firstFocusableElement = containerElement?.querySelector(
"[tabindex='0']"
) as HTMLElement | null;
const lastFocusableElement = containerElement?.querySelectorAll(
"[tabindex]:not([tabindex='-1'])"
)[
containerElement?.querySelectorAll("[tabindex]:not([tabindex='-1'])")
.length - 1
] as HTMLElement | null;
Iif (event.key !== "Tab") return;
Iif (!event.shiftKey && event.target === lastFocusableElement) {
firstFocusableElement?.focus();
event.preventDefault();
}
Iif (event.shiftKey && event.target === firstFocusableElement) {
lastFocusableElement?.focus();
event.preventDefault();
}
};
containerRef.current?.focus();
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [containerRef]);
};
|