useModal
import React, { PropsWithChildren } from 'react';
import styled from 'styled-components';
interface ModalDefaultType {
onClickToggleModal: () => void;
}
function Modal({
onClickToggleModal,
children,
}: PropsWithChildren<ModalDefaultType>) {
return (
<ModalContainer>
<DialogBox>{children}</DialogBox>
<Backdrop
onClick={(e: React.MouseEvent) => {
e.preventDefault();
if (onClickToggleModal) {
onClickToggleModal();
}
}}
/>
</ModalContainer>
);
}
const ModalContainer = styled.div`
width: 300px;
height: auto;
display: flex;
align-items: center;
justify-content: center;
position: absolute;
`;
const DialogBox = styled.dialog`
display: flex;
flex-direction: column;
align-items: center;
border: none;
border-radius: 3px;
box-shadow: 0 0 30px rgba(30, 30, 30, 0.185);
box-sizing: border-box;
background-color: white;
z-index: 10000;
`;
const Backdrop = styled.div`
width: 10000px;
height: 10000px;
position: fixed;
top: 0;
z-index: 9999;
background-color: rgba(0, 0, 0, 0.2);
`;
export default Modal;
const [isOpenModal, setOpenModal] = useState<boolean>(false);
const onClickToggleModal = useCallback(() => {
setOpenModal(!isOpenModal);
}, [isOpenModal]);
...
{isOpenModal && (
<Modal onClickToggleModal={onClickToggleModal}>
<div>๋ชจ๋ฌ์์ชฝ๋ชจ์</div>
</Modal>
)}
<button onClick={onClickToggleModal}>
<div>๋ชจ๋ฌ๋ฒํผ<div/>
</button>
์ฌ์ฉํ ๋๋ง๋ค ์ฌ์ฉํ๋ ๊ณณ์์ ์ํ๋ฅผ ์ ์ํด์ ์ฌ์ฉํด์ผํ๋ค๋ ๋ถํธํจ๋ ์๊ณ ,
๋ชจ๋ ๋ชจ๋ฌ์ด ๋ชจ๋ ๊ฐ์ ์คํ์ผ์ ๊ฐ์ง๊ณ ์์ง ์๊ธฐ ๋๋ฌธ์ hook์ผ๋ก ๋ง๋ค์ด์ ์ฌ์ฉํด์ผ ๊ฒ ๋ค๊ณ ์๊ฐํ์
//useModal.ts
import { useCallback, useState } from 'react';
const useModal = () => {
const [isOpenModal, setOpenModal] = useState<boolean>(false);
const handleModal = useCallback(() => {
setOpenModal(!isOpenModal);
}, [isOpenModal]);
return {
isOpenModal,
handleModal,
};
};
export default useModal;
const { isOpenModal, handleModal } = useModal();
...
{isOpenModal && <div>๋ชจ๋ฌ์์ชฝ๋ชจ์.</div>}
<button onClick={handleModal}>๋ฒํผ</button>
๋ชจ๋ฌ์ ๋์ธ ๋๋ ์ํ๊ฐ ์ ๋ณ๊ฒฝ์ด ๋์์ง๋ง, z-index๋ก ๊ตฌํ์ ํ์ ๋, ๊ธฐ์กด ๋ฒํผ์ ๋๋ฅด์ง ๋ชปํ๊ธฐ ๋๋ฌธ์ ์ํ๋ฅผ ๋ค์ ๋ณ๊ฒฝ์ํค์ง ๋ชปํด์, ๋ซ๊ธฐ๋ฅผ ํ ์ ์์๋ค.
๊ทธ๋์ ๋ชจ๋ฌ ๋ด๋ถ์ ๋ซ๊ธฐ ๋ฒํผ์ ์ถ๊ฐํด ์ฃผ์๋ค.
const { isOpenModal, handleModal } = useModal();
...
{isOpenModal &&
(
<div>
<button onClick={handleModal}>๋ซ๊ธฐ</button>
<div>๋ชจ๋ฌ ์์ชฝ ๋ชจ์</div>
</div>
)}
<button onClick={handleModal}>๋ฒํผ</button>
๋ชจ๋ฌ ๋ด๋ถ์์๋ handleModal
์ ํตํด์ state๋ฅผ ๊ด๋ฆฌํด ์คฌ๋ค.
์ด๋ฐ์์ผ๋ก ๊ตฌํํ์ ๋, ๋งค ๋ฒ ์ปดํฌ๋ํธ๋ฅผ ๋ง๋ค์ด์ ๊ทธ์ ๋ง๊ฒ props๋ฅผ ์ ๋ฌํด ์ค์ผํ๋ ๋ถํธํจ์ด ์์๋ค. modal์ container component๋ฅผ ๋ง๋ค์ด์ ๊ด๋ฆฌํ๋ ค๊ณ ํ๋ค.