끄적이는 개발노트
react-modal 본문
728x90
이번 포스트에서는 모달창을 생성해주는 npm인 react-modal에 대해 알아본다.
import ReactModal from "react-modal";
import { useEffect, useState } from "react";
import { IoIosCloseCircle } from "react-icons/io";
const HeoTest = () => {
const [modalOpen, setModalOpen] = useState<boolean>(false); // modal 창 여부
// modal 창 팝업 시 뒤에 배경 scroll 막기
useEffect(() => {
modalOpen === true
? (document.body.style.overflow = "hidden")
: (document.body.style.overflow = "unset");
}, [modalOpen]);
// modal 창 닫기
const closeModal = () => {
setModalOpen(false);
};
return (
<div>
<button
type="button"
onClick={() => {
setModalOpen(true);
}}
>
모달창 열기
</button>
<ReactModal
isOpen={modalOpen}
style={{
overlay: {
position: "fixed",
zIndex: 9999,
top: 0,
left: 0,
width: "100vw",
height: "100vh",
background: "rgba(71, 71, 71, 0.75)",
display: "flex",
alignItems: "center",
justifyContent: "center",
},
content: {
background: "white",
width: "500px",
height: "800px",
maxWidth: "calc(100vw - 2rem)",
maxHeight: "calc(100vh - 2rem)",
overflowY: "auto",
position: "relative",
border: "1px solid #ccc",
borderRadius: "0.3rem",
boxShadow: "0px 10px 15px rgba(61,61,61,1)",
inset: 0,
},
}}
>
<div style={{display: "flex", justifyContent: "flex-end"}}>
<button type="button" onClick={closeModal}>
<IoIosCloseCircle />
</button>
</div>
<div>모달이랍니다.</div>
</ReactModal>
</div>
)
}
export default HeoTest
모달창 오픈 여부를 boolean 타입을 가지는 state로 관리한다.
본인의 경우, 해당 모달이 열려있으면 뒤에 스크롤을 막기 위해서 useEffect를 활용했다.
모달의 디자인은 따로 관리해도 되지만, 이번 예시 코드에서는 직접 타이핑하여 overlay와 content를 디자인했다.
여기에 modal option 혹은 local storage 등을 통해 여러 모달들을 옵션 별로 열게도 설정할 수 있다.
본인의 경우, 이런 식으로 컴포넌트로 따로 뺀 후, switch case 문을 활용해 여러 모달을 option과 props로 제어 가능하게끔 설정했다.
이를 통해, 비교적 간결한 코드로 modal을 제어할 수 있게 됐다.
직접 실행해보면 위와 같은 화면으로 모달이 잘 열리는 것을 확인할 수 있다.
728x90
'JavaScript > React.js' 카테고리의 다른 글
React.js - 쿠키 사용(js-cookie) (0) | 2023.06.22 |
---|---|
useInterval을 활용한 타이머 기능 만들기 (0) | 2023.02.01 |
react-day-picker (0) | 2022.01.27 |
react-hook-form 사용법(2) (0) | 2022.01.27 |
react-hook-form 사용법(1) (0) | 2021.11.22 |