Skip to content

Commit

Permalink
Merge pull request dostonnabotov#2 from jacobtyq/main
Browse files Browse the repository at this point in the history
Use Escape key to close snippet modal
  • Loading branch information
dostonnabotov authored Dec 29, 2024
2 parents 4b25986 + 0a2ee6b commit afae80d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/components/SnippetModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { CloseIcon } from "./Icons";
import CodePreview from "./CodePreview";
import { SnippetType } from "../types";
import slugify from "../utils/slugify";
import useEscapeKey from "../hooks/useEscapeKey";

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

return ReactDOM.createPortal(
<div className="modal-overlay">
Expand Down
16 changes: 16 additions & 0 deletions src/hooks/useEscapeKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { useEffect } from "react"

const useEscapeKey = (onEscapeEvent: () => void) => {
useEffect(() => {
const handleEscape = (event: { key: string }) => {
if (event.key === "Escape") onEscapeEvent();
}
window.addEventListener("keydown", handleEscape);

return () => {
window.removeEventListener("keydown", handleEscape);
}
}, [onEscapeEvent]);
};

export default useEscapeKey;

0 comments on commit afae80d

Please sign in to comment.