NextJS에 간단한 모달창 띄우기(next : 16.2.2 ver, react : 19.2.4 ver)
NextJS에 간단한 모달을 띄우는 방법 입니다.
아래는 이번글에서 작성한 코드의 dependencies 및 devDependencies입니다.
"dependencies": {
"next": "16.2.2",
"react": "19.2.4",
"react-dom": "19.2.4"
},
"devDependencies": {
"@biomejs/biome": "2.2.0",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"typescript": "^5"
}
폴더 및 파일 구조
src
|-app
| |- page.tsx
|- component
|- modal
|- TestModal.module.css
|- TestModal.tsx
page.tsx파일은 루트 페이지로 "Open Modal"로 작성된 버튼이 하나만 있습니다. 해당 버튼을 누르게 되면 "TestModal.tsx"페이지가 모달창으로 열립니다.
// src\app\page.tsx
'use client';
import { TestModal } from "@/component/modal/TestModal";
import { useState } from "react";
export default function Home() {
// 모달창의 상태를 기록(true면 모달창이 열림)
const [modalOpen, setModalOpen] = useState(false);
// 모달창을 연다. modalOpen을 true로 설정
const handleOpenModal = () => {
setModalOpen(true);
}
// 모달창을 닫는다. modalOpen을 false로 설정
const handleCloseModal = () => {
setModalOpen(false);
}
return (
<>
<button onClick={handleOpenModal}>Open Modal</button>
{modalOpen && (<TestModal onClose={handleCloseModal} />)}
</>
);
}
먼저 초기 화면을 구성하는 코드이다. handleOpenModal, handleCloseModal을 이용해서 모달창을 불러오거나 닫는다. modalOpen값이 true이면 TestModal 창을 불러온다.
// src\component\modal\TestModal.tsx
import style from './TestModal.module.css';
export function TestModal({ onClose }: { onClose: () => void }) {
return (
// overlay (배경 전체 영역)
// 화면 전체를 덮는 레이어
<div className={style.overlay}>
{/* // 부모(overlay)로 클릭 이벤트 전달 차단 */}
<div className={style.modal} onClick={(e) => e.stopPropagation()}>{ }
<h1>Test Modal</h1>
{/* 닫기버튼 */}
<button onClick={onClose}>close</button>
</div>
</div>
);
}
/* src\component\modal\TestModal.module.css */
.overlay {
position: fixed;
/*
viewport(화면) 기준으로 고정
스크롤해도 따라다님
부모영향 안받음
*/
top: 0;
/* 화면의 가장 왼쪽부터 시작 */
left: 0;
/* 화면의 가장 위쪽부터 시작 */
width: 100vw;
/* 너비는 화면 전체 */
height: 100vh;
/* 높이는 화면 전체 */
display: flex;
justify-content: center;
align-items: center;
background: rgba(0,0,0,0.5);
/*
배경은 반투명 검정
뒤는 화면 흐리게
*/
z-index: 9999;
/*
다른요소 위로 올림
값이 낮으면 뒤에 가려짐. 모달을 항상 최상단에 위치
*/
}
.modal {
background: white;
padding: 20px;
border-radius: 10px;
}
위와 같이 코드를 작성할 경우 닫기까지 기능하는 모달창을 생성
댓글
댓글 쓰기