Skip to content

Instantly share code, notes, and snippets.

@moaaz-bhnas
Created August 9, 2021 19:05
Show Gist options
  • Save moaaz-bhnas/aeef1101b731ca96622c5f316feaefbd to your computer and use it in GitHub Desktop.
Save moaaz-bhnas/aeef1101b731ca96622c5f316feaefbd to your computer and use it in GitHub Desktop.
Trap focus
const handleKeyDown = useCallback(
(event, firstInteractive, lastInteractive, close, handleSubmit) => {
const { target, key, shiftKey } = event;
if (key === "Tab" && shiftKey && target === firstInteractive) {
event.preventDefault();
lastInteractive.focus();
}
if (key === "Tab" && !shiftKey && target === lastInteractive) {
event.preventDefault();
firstInteractive.focus();
}
if (key === "Escape") {
close();
}
if (key === "Enter") {
event.preventDefault();
handleSubmit();
}
},
[]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment