리액트(React): 모달 팝업시 뒷배경(오버레이) 스크롤 되지 않게 하기
body 태그의 css를 변경합니다. position을 fixed로 하고, top의 위치를 현재 스크롤 위치로 설정한 뒤 overflow-y: scroll; width: 100%; 을 추가 지정하면 스크롤바로 인해 배경의 위치가 움직이지 않고도 스크롤 방지를 할 수 있습니다.
useEffect를 사용해 css를 변경하며, 모달이 사라질 때에는 useEffect의 return을 사용해 body의 cssText를 리셋시킨 다음 window,scroll을 이용해 현재 스크롤 위치로 강제 이동시킵니다. 참고로 useEffect의 return 절은 컴포넌트가 unmount 될 때 호출됩니다.
스크롤 방지 모달 스크롤 방지 스크롤 안되게 리액트 모달 스크롤 안되게
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import React, { useEffect } from 'react';
export const Modal = (props) => {
// 모달 오버레이에서 스크롤 방지
useEffect(() => {
document.body.style.cssText = `
position: fixed;
top: -${window.scrollY}px;
overflow-y: scroll;
width: 100%;`;
return () => {
const scrollY = document.body.style.top;
document.body.style.cssText = '';
window.scrollTo(0, parseInt(scrollY || '0', 10) * -1);
};
}, []);
return (
<>
{isDisplay && (
`<Container>
<ModalOverlay />
<ModalWindow />
</Container>`
)}
</>
);
};
참고
This post is licensed under
CC BY 4.0
by the author.
