ํด๋ฆญ ์ ๋ซํ๋ ๋ชจ๋ฌ ์ ์
useModal
ํ
import {
Dispatch,
MutableRefObject,
SetStateAction,
useCallback,
useEffect,
useRef,
useState,
} from "react";
const useModal = (): [
MutableRefObject<HTMLElement | null>,
boolean,
Dispatch<SetStateAction<boolean>>
] => {
const modalRef = useRef<null | HTMLElement>(null);
const [isOpen, setIsOpen] = useState(false);
// 2022/05/01 - ํด๋ฆญ ์ ๋ชจ๋ฌ ๋ซ๊ธฐ ์ด๋ฒคํธ - by 1-blue
const handleCloseModal = useCallback(() => {
if (isOpen) setIsOpen(false);
}, [isOpen]);
// 2022/05/01 - ๋ชจ๋ฌ ๋ซ๊ธฐ ์ด๋ฒคํธ ๋ฑ๋ก - by 1-blue
useEffect(() => {
setTimeout(() => window.addEventListener("click", handleCloseModal), 0);
return () => window.removeEventListener("click", handleCloseModal);
}, [handleCloseModal]);
return [modalRef, isOpen, setIsOpen];
};
export default useModal;
Modal
์ปดํฌ๋ํธimport { forwardRef, useEffect } from "react";
// util
import { combineClassNames } from "@src/libs/util";
type Props = {
children: React.ReactChild;
className?: string;
noScroll?: boolean;
primary?: boolean;
};
// eslint-disable-next-line react/display-name
const Modal = forwardRef<HTMLElement, Props>(
({ children, className, noScroll, primary }, ref) => {
// 2022/05/01 - ๋ชจ๋ฌ์ฐฝ open ์ ์คํฌ๋กค ๊ธ์ง - by 1-blue
useEffect(() => {
if (!noScroll) return;
document.body.style.overflow = "hidden";
return () => {
document.body.style.overflow = "auto";
};
}, [noScroll]);
return (
<aside
className={combineClassNames(
"z-10",
primary
? "fixed -top-4 left-0 bottom-0 right-0 z-10 bg-black/80 flex justify-center items-center"
: "",
className ? className : ""
)}
ref={ref}
>
{children}
</aside>
);
}
);
export default Modal;
// 2022/05/01 - ๊ฒ์๊ธ ์ญ์ ๋ชจ๋ฌ - by 1-blue
const [modalRef, isOpen, setIsOpen] = useModal();
// jsx
{isOpen && (
<Modal ref={modalRef} noScroll primary>
<form className="flex flex-col bg-zinc-900 p-8 rounded-md space-y-4 w-[400px]">
<span className="font-bold text-2xl">ํฌ์คํธ ์ญ์ </span>
<span>์ ๋ง ํฌ์คํธ๋ฅผ ์ญ์ ํ์๊ฒ ์ต๋๊น?</span>
<div />
<div className="text-right space-x-2">
<button
type="button"
className="px-6 py-2 bg-indigo-400 rounded-md hover:bg-indigo-500"
>
์ทจ์
</button>
<button
type="button"
className="px-6 py-2 bg-indigo-400 rounded-md hover:bg-indigo-500"
onClick={() => removePost({})}
>
ํ์ธ
</button>
</div>
</form>
</Modal>
)}