모달의 뒷 배경 스크롤을 막고 정중앙에 띄우기

modric·2024년 3월 21일
0

세이치즈

목록 보기
6/9

문제

모달의 동작이 바람직하지 않다. 모달이 떠도 뒷배경이 길면 스크롤이 가능하다. 스크롤 bottom 끝에서 모달을 누르면 모달이 스크롤 top에서 부터 위치하는 바람에 내가 보는 화면 중앙에서 벗어나있다.

해결 코드

정상적인 모달은 ?

  1. 모달떴을때 뒤에 스크롤 움직이면 안된다.
  2. 모달이 보고 있는 화면에서 가운데에 떠야한다
// 모달 컴포넌트
생략...
export default function CardModal() {
  생략...
  useEffect(() => {
    // 1-1. 모달 열리면 본문 스크롤 방지
    document.body.style.overflow = "hidden";
    // 2. 현재 보고 있는 스크롤의 왼쪽 top을 가운데 정렬할 기준 top으로 해줌
    const modalbg = document.getElementsByClassName("modalBackdrop")[0]; // Get the first element with the class name
    const currentTop = window.scrollY + "px";
    modalbg.style.top = currentTop; // Set the top CSS property of the element
  }, []); // Empty dependency array to run the effect only once when the component mounts


  return (
    <>
      <div className="modalBackdrop">
        <div className="modal">
          생략...
              <button
                onClick={() => {
                  // 1-2. 모달 닫으면 본문 스크롤 허용
                  document.body.style.overflow = "auto";
                  dispatch(closeModal());
                }}
              >
                닫기
              </button>
            </>
          )}
        </div>
      </div>
    </>
  );
}

이제 모달이 1번 2번 조건을 만족하며 바람직하게 움직인다

profile
Github: s01k1m / Email: sk618dev@gmail.com

0개의 댓글