Skip to content

Commit

Permalink
close modal on escape key press
Browse files Browse the repository at this point in the history
  • Loading branch information
cdleveille committed Jun 1, 2024
1 parent f12b959 commit 23c2067
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"version": "2.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"dev": "next dev --turbo",
"build": "next build",
"start": "next start",
"lint": "next lint"
Expand Down
1 change: 1 addition & 0 deletions src/components/DiscDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { DiscContext } from "@components";
import { hexToRgba } from "@util";

import type { DiscDetailProps } from "@types";

export const DiscDetail = ({ name_slug }: DiscDetailProps) => {
const { discs } = useContext(DiscContext);
const disc = discs.find(disc => disc.name_slug === name_slug);
Expand Down
7 changes: 5 additions & 2 deletions src/components/DiscModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@

import { useRouter } from "next/navigation";

import { useKeyPress } from "@hooks";
import { Modal as MuiModal } from "@mui/material";

import type { ModalProps } from "@types";

export function DiscModal({ children }: ModalProps) {
const router = useRouter();
const onClose = () => router.back();

useKeyPress("Escape", onClose);

return (
<MuiModal open={true} className="mui-fixed">
<MuiModal open={true} className="mui-fixed" disableEscapeKeyDown>
<div className="modal" onClick={onClose}>
{children}
</div>
Expand Down
1 change: 1 addition & 0 deletions src/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./useKeyPress";
13 changes: 13 additions & 0 deletions src/hooks/useKeyPress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"use client";

import { useEffect } from "react";

export const useKeyPress = (key: string, action: () => void) => {
useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
if (e.key === key) action();
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [key, action]);
};

0 comments on commit 23c2067

Please sign in to comment.