Skip to content

Instantly share code, notes, and snippets.

@brunosabot
Created November 11, 2021 21:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brunosabot/41f8acd09fee652c24d4575e29dd5e42 to your computer and use it in GitHub Desktop.
Save brunosabot/41f8acd09fee652c24d4575e29dd5e42 to your computer and use it in GitHub Desktop.
import { useCallback, useEffect } from "react";
export default function useEscape(active: boolean, onClose: () => void) {
const onEchap = useCallback(
(event) => {
if (event.keyCode === 27) {
onClose();
}
},
[onClose]
);
useEffect(() => {
if (active) {
window.addEventListener("keydown", onEchap);
return () => {
window.removeEventListener("keydown", onEchap);
};
}
}, [onEchap, active]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment