멈멈-토이프로젝트(next.js)2
모달 창띄우고 스크롤 금지
순9
2024. 11. 28. 14:30
728x90
기존에는
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
setIsMounted(true);
if (!dialogRef.current?.open) {
dialogRef.current?.showModal();
dialogRef.current?.scrollTo({
top: 0,
});
}
}, [value]);
isMounted의 값에 따라 서버사이드 렌더링 방지
문제 사항은
모달은 정상으로 뜨고 body도 스크롤 되어서 모달이 뜰때 body는 스크롤 금지
useEffect(() => {
setIsMounted(true); // 첫 렌더링 이후 상태를 true로 변경
}, []);
useEffect(() => {
if (isMounted && !dialogRef.current?.open) {
dialogRef.current?.showModal();
dialogRef.current?.scrollTo({
top: 0,
});
// 모달 켜질 시 body스크롤 금지
document.body.style.overflow = "hidden";
}
return () => {
document.body.style.overflow = "auto"; // 모달 닫힐 때 스크롤 복구
};
}, [value]);
조건을 추가 해서 두개의 값이 같으면 모달 뜰때 body스크롤 금지
같지 않으면 스크롤됨
이렇게 하니까 스크롤이 안 켜짐
useEffect(() => {
setIsMounted(true);
if (isMounted&& !dialogRef.current?.open) {
dialogRef.current?.showModal();
dialogRef.current?.scrollTo({
top: 0,
});
// 모달 켜질 시 body스크롤 금지
document.body.style.overflow = "hidden";
}
return () => {
document.body.style.overflow = "auto"; // 모달 닫힐 때 스크롤 복구
};
}, [value]);
위 코드로 변경 함
첫 렌더링에서
setIsMounted(true); 상태 변경됨
조건문은 맞지 않아서 지나감
document.body.style.overflow = "auto"; 설정 됨
의존성 배열 변경 되면
조건문 실행 됨
document.body.style.overflow = "hidden"; 설정 됨