Code Used:
const handleKeyPress = (event: KeyboardEvent) => {
const key = Number(event.key);
if (key >= 1 && key <= totalCards) {
setSelected(key - 1);
}
if (event.key === "Tab") {
event.preventDefault();
const focusableElements = document.querySelectorAll(".allowed-tab");
const focusArray = Array.from(focusableElements);
if (focusArray.length > 0) {
const currentIndex = focusArray.indexOf(document.activeElement as Element);
const nextIndex = currentIndex === -1 ? 0 : (currentIndex + 1) % focusArray.length;
(focusArray[nextIndex] as HTMLElement).focus();
}
}
};
useEffect(() => {
// only the function should be called inside useEffect
window.addEventListener("keydown", handleKeyPress);
return () => window.removeEventListener("keydown", handleKeyPress);
}, []);