|
1 | 1 | import ModalPortal from "./ModalPortal"; |
2 | | -import { useModalStore } from "../../../store/useModalStore"; |
| 2 | +import { useModalStore } from "@store/useModalStore"; |
3 | 3 | import { Inside, ModalFrame, Overlay } from "./modalStyle"; |
4 | | -import { useEffect } from "react"; |
| 4 | +import { useEffect, useCallback, useRef } from "react"; |
5 | 5 | import { useModal } from "@hooks/useModal"; |
6 | 6 | import { modalComponents } from "./modalComponent"; |
7 | 7 |
|
8 | 8 | export default function Modal() { |
9 | 9 | const { showModal, currentModal, modalColor } = useModalStore(); |
10 | 10 | const { closeModal } = useModal(); |
| 11 | + const scrollYRef = useRef(0); |
11 | 12 |
|
12 | | - if (!showModal) return null; |
| 13 | + if (!showModal || !currentModal) return null; |
13 | 14 |
|
14 | 15 | useEffect(() => { |
15 | | - document.body.style.cssText = ` |
16 | | - position: fixed; |
17 | | - top: -${window.scrollY}px; |
18 | | - overflow-y: scroll; |
19 | | - width: 100%;`; |
| 16 | + scrollYRef.current = window.scrollY; |
| 17 | + document.body.style.overflow = "hidden"; |
| 18 | + |
20 | 19 | return () => { |
21 | | - const scrollY = document.body.style.top; |
22 | | - document.body.style.cssText = ""; |
23 | | - window.scrollTo(0, parseInt(scrollY || "0", 10) * -1); |
| 20 | + document.body.style.overflow = "auto"; |
| 21 | + window.scrollTo(0, scrollYRef.current); |
24 | 22 | }; |
25 | 23 | }, []); |
26 | 24 |
|
27 | | - useEffect(() => { |
28 | | - const onKeydownEscape = (e: KeyboardEvent) => { |
29 | | - if (e.key === "Escape") { |
30 | | - closeModal(); |
31 | | - } |
32 | | - }; |
| 25 | + const onKeydownEscape = useCallback( |
| 26 | + (e: KeyboardEvent) => { |
| 27 | + if (e.key === "Escape") closeModal(); |
| 28 | + }, |
| 29 | + [closeModal], |
| 30 | + ); |
33 | 31 |
|
| 32 | + useEffect(() => { |
34 | 33 | document.addEventListener("keydown", onKeydownEscape); |
35 | 34 |
|
36 | 35 | return () => { |
37 | 36 | document.removeEventListener("keydown", onKeydownEscape); |
38 | 37 | }; |
39 | | - }, [closeModal]); |
| 38 | + }, [onKeydownEscape]); |
40 | 39 |
|
41 | 40 | return ( |
42 | 41 | <ModalPortal> |
43 | 42 | <ModalFrame onClick={closeModal}> |
44 | | - {modalColor === "white" ? ( |
45 | | - <Overlay onClick={closeModal}> |
46 | | - <Inside onClick={(e) => e.stopPropagation()} styleKey={modalColor}> |
47 | | - {currentModal ? modalComponents[currentModal] : null} |
48 | | - </Inside> |
49 | | - </Overlay> |
50 | | - ) : ( |
| 43 | + <Overlay modalColor={modalColor}> |
51 | 44 | <Inside |
52 | 45 | onClick={(e) => e.stopPropagation()} |
53 | 46 | styleKey={modalColor as "white" | "blue"} |
54 | 47 | > |
55 | | - {currentModal ? modalComponents[currentModal] : null} |
| 48 | + {modalComponents[currentModal]} |
56 | 49 | </Inside> |
57 | | - )} |
| 50 | + </Overlay> |
58 | 51 | </ModalFrame> |
59 | 52 | </ModalPortal> |
60 | 53 | ); |
|
0 commit comments