atom에서 modalState 불러오기
const setModal = useSetRecoilState(modalState);
modal을 호출할 때 setModal 함수 내부에 속성값 지정
modalProps 타입 참고
interface ModalProps {
isOpen: boolean;
closeButton?: boolean;
title?: string;
content?: string;
buttonNum?: 0 | 1 | 2;
handleConfirm?: () => void;
handleCancel?: () => void;
}
setModal 호출
setModal({
isOpen: true,
closeButton: true,
title: "로그인이 필요합니다!",
content:
"항공권 구매를 위해 로그인이 필요합니다.\\n로그인 페이지로 이동하시겠습니까?",
buttonNum: 2,
});
isOpen : 모달 활성화 여부
closeButton : X 버튼 유무
title : 모달 타이틀
content : 모달 내용 ⇒ 줄바꿈이 필요할 경우 \\n 추가하기!
자유로운 줄바꿈을 위해 컨텐트를 작성할 때는 <pre> 태그를 사용했다.
<pre className="modal-content">{content}</pre>
buttonNum
handleConfirm : 확인 버튼 클릭 시 실행할 콜백함수
handleCancel : 취소 버튼 클릭 시 실행할 콜백함수
모달 코드
import { modalState } from "@/atoms/atoms";
import { useRecoilValue, useSetRecoilState } from "recoil";
import Button from "../Button/Button";
import "./Modal.scss";
const Modal = () => {
const {
isOpen,
closeButton = "true",
title,
content,
buttonNum,
handleConfirm,
handleCancel,
} = useRecoilValue(modalState);
const setModal = useSetRecoilState(modalState);
// 모달 닫기
const handleClose = () => {
setModal({
isOpen: false,
});
};
// 모달 오픈 시 배경 스크롤 방지
// if (isOpen) {
// document.body.setAttribute(
// "style",
// "position: fixed; overflow-y: hidden; width: 100vw;"
// );
// } else {
// document.body.setAttribute(
// "style",
// "position: unset; overflow-y: unset; width: unset;"
// );
// }
return (
<>
{isOpen && (
<div className="modal-layout">
<div className="modal-window">
{closeButton && (
<button className="modal-close" onClick={handleClose}>
<img src="img/icon-close-black.svg" alt="닫기" />
<i className="hidden">모달 닫기</i>
</button>
)}
<h3 className="modal-title">{title}</h3>
<pre className="modal-content">{content}</pre>
<>
{buttonNum && (
<div className="modal-button-container">
{buttonNum > 1 && (
<Button
size="full"
bgColor="light"
onClick={() => {
if (handleCancel) {
handleCancel();
}
handleClose();
}}
>
취소
</Button>
)}
<Button
size="full"
onClick={() => {
if (handleConfirm) {
handleConfirm();
}
handleClose();
}}
>
확인
</Button>
</div>
)}
</>
</div>
</div>
)}
</>
);
};
export default Modal;