Skip to content

Commit afae80d

Browse files
authored
Merge pull request #2 from jacobtyq/main
Use Escape key to close snippet modal
2 parents 4b25986 + 0a2ee6b commit afae80d

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

src/components/SnippetModal.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { CloseIcon } from "./Icons";
55
import CodePreview from "./CodePreview";
66
import { SnippetType } from "../types";
77
import slugify from "../utils/slugify";
8+
import useEscapeKey from "../hooks/useEscapeKey";
89

910
type Props = {
1011
snippet: SnippetType;
@@ -19,6 +20,7 @@ const SnippetModal: React.FC<Props> = ({
1920
}) => {
2021
const modalRoot = document.getElementById("modal-root");
2122
if (!modalRoot) return null;
23+
useEscapeKey(handleCloseModal);
2224

2325
return ReactDOM.createPortal(
2426
<div className="modal-overlay">

src/hooks/useEscapeKey.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { useEffect } from "react"
2+
3+
const useEscapeKey = (onEscapeEvent: () => void) => {
4+
useEffect(() => {
5+
const handleEscape = (event: { key: string }) => {
6+
if (event.key === "Escape") onEscapeEvent();
7+
}
8+
window.addEventListener("keydown", handleEscape);
9+
10+
return () => {
11+
window.removeEventListener("keydown", handleEscape);
12+
}
13+
}, [onEscapeEvent]);
14+
};
15+
16+
export default useEscapeKey;

0 commit comments

Comments
 (0)