모달 스크롤방지

devMarco·2022년 5월 4일
0

모달에서 확인 하기

useEffect(() => {
	console.log('mount')
return () => console.log('unmount')
}, [])

확인
모달이 뜨면 mount
모달이 꺼지면 unmount

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>`
      )}
    </>
  );
};

0개의 댓글