yarn add react-modal
yarn add @types/react-modal
yarn add @tailwindcss/forms
// tailwind.config.js
module.exports = {
plugins: [
require('@tailwindcss/forms'),
// 다른 설정들...
],
};
import { atom } from 'recoil';
export const modalState = atom<boolean>({
key: 'modalState',
default: false,
});
import React from 'react';
import ReactModal from 'react-modal';
import { useRecoilState } from 'recoil';
import { modalState } from '@/recoil/modalState';
const customModalStyles: ReactModal.Styles = {
overlay: {
backgroundColor: "rgba(0, 0, 0, 0.4)",
width: "100%",
height: "100vh",
zIndex: 10,
position: "fixed",
top: 0,
left: 0,
},
content: {
width: "360px",
height: "180px",
zIndex: 150,
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
borderRadius: "10px",
boxShadow: "2px 2px 2px rgba(0, 0, 0, 0.25)",
backgroundColor: "white",
justifyContent: "center",
overflow: "auto",
},
};
interface ModalProps {
children: React.ReactNode;
onRequestClose: () => void;
}
const Modal: React.FC<ModalProps> = ({ children, onRequestClose }) => {
const [isOpen, setIsOpen] = useRecoilState(modalState);
// 모달을 닫을 때 onRequestClose 함수 호출
const closeModal = () => {
onRequestClose();
};
return (
<ReactModal
isOpen={isOpen}
style={customModalStyles} // 스타일 적용
onRequestClose={closeModal} // 모달 창 닫기 요청을 받을 때 호출
shouldCloseOnOverlayClick={true} // 외부 클릭으로 모달 닫기 활성화
>
<div className="modal-content">
{children}
<button onClick={closeModal}>닫기</button>
</div>
</ReactModal>
);
};
export default Modal;
이름 | 기능 |
---|---|
isOpen | 모달 창이 표시되어야 하는지 여부를 설명하는 boolean 값이다. 즉, 해당 값이 true여야 모달 창이 열리는 것이다. |
onRequestClose | 모달이 닫힐 때 실행될 함수를 의미한다. 즉,사용자가 모달을 닫으려고 할 때 실행되는 함수이다. |
style | 모달 창과 모달 창 바깥에 대한 style을 지정해준다. |
shouldCloseOnOverlayClick | 팝업창이 아닌 바깥 부분에서 클릭하였을 때, 닫히도록 할 것인지에 대한 처리이다. 기본값으로는 true를 가지고 있다. |
shouldCloseOnOverlayClick | 외부를 클릭했을 때 모달이 닫히도록 설정할 수 있다. |
const Router = () => {
const [isOpen, setIsOpen] = useRecoilState(modalState);
const openModal = () => {
setIsOpen(true);
};
const closeModal = () => {
setIsOpen(false);
};
return (
<BrowserRouter>
<Routes>
{/* ... */}
</Routes>
<button onClick={openModal}>모달 열기</button>
<Modal onRequestClose={closeModal}>
<h2>모달 제목</h2>
<p>모달 내용을 여기에 추가합니다.</p>
</Modal>
</BrowserRouter>
);
};