[React] 모달 창 스크롤 막기

임홍원·2024년 1월 31일
post-thumbnail

모달창을 구현하고 배경이 스크롤되는 문제점이 있었다.
이는 사용자 경험적인 측면에서 좋지 않기때문에 모달 배경 스크롤을 막았다.

시도해본 방법들

1. css

css에서 position을 fixed로 해놓고 overflow를 hidden으로 주면 해결된다는 방식이 있었다.
그치만 내 코드는 이미 둘 다 적용되어있었다.

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 3;
  overflow: hidden;
}

2. documet.body.style

모달 오버레이 창이 열렸을때 body overflow를 hidden으로 준다.
이 방법으로 뒷 배경 스크롤이 막히게 되었다.

<button className={styles['modify-btn']} onClick={() => {
                toggleModal();
                document.body.style.overflow = 'hidden';
              }}>
<button className={styles['close-btn']} onClick={() => {
        toggleModal();
        document.body.style.overflow = 'auto';
      }}>
        <ModalCloseSvg />
      </button>

모달이 닫혔을때는 overflow를 auto로 준다.

profile
Frontend Developer

0개의 댓글