Framework/React

[React] Modal νŒμ—…μ‹œ 뒷배경이 슀크둀 λ˜μ§€ μ•Šκ²Œ ν•˜λŠ” 방법

yuri lee 2022. 8. 30. 23:35
λ°˜μ‘ν˜•

Intro 

λ¦¬μ•‘νŠΈμ—μ„œ Modal νŒμ—…μ‹œ 뒷배경이 슀크둀 λ˜μ§€ μ•Šκ²Œ ν•˜λŠ” 방법에 λŒ€ν•΄ μ†Œκ°œν•˜κ³ μž ν•©λ‹ˆλ‹€. 

 

How to do 

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);
    };
  }, []);
  ...
};

useEffectλ₯Ό μ‚¬μš©ν•˜μ—¬ Modal νŒμ—…λœ μƒνƒœλΌλ©΄ λ‹€μŒμ˜ CSSλ₯Ό μ μš©μ‹œν‚€κ³ , 그게 μ•„λ‹ˆλΌλ©΄ CSSλ₯Ό reset μ‹œν‚€λ©΄ λ©λ‹ˆλ‹€. 

 

Reference

http://yoonbumtae.com/?p=3776

λ°˜μ‘ν˜•