[react]Modal ํ์ ์ ๋ท๋ฐฐ๊ฒฝ ์คํฌ๋กค ๋์ง ์๊ฒ ํ๊ธฐ
Modal components๋ฅผ ๋ง๋ค์๋๋ฐ, ๋ชจ๋ฌ css position ์์ฑ์ธ `fixed`๋ฅผ ์ ์ฉํด๋ ๋ท ๋ฐฐ๊ฒฝ์ด ์คํฌ๋กค์ด ๋๋ ๋ฌธ์ ๋ฅผ ๊ฒช์๋ค. ๊ทธ๋์ ์ด๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด ๊ตฌ๊ธ๋ง์ ํ๋ค.
// ๋ชจ๋ฌ ์ค๋ฒ๋ ์ด์์ ์คํฌ๋กค ๋ฐฉ์ง
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);
};
}, []);
์ด๋ react hook ์ค ํ๋์ธ useEffect๋ฅผ ํตํด ์ด๋ฅผ ํด๊ฒฐํ๋ ๋ฐฉ๋ฒ์ด๋ค.
`body`ํ๊ทธ์ css๋ฅผ ๋ณ๊ฒฝํด position์ fixed๋ก ํ๊ณ , top์ ์์น๋ฅผ ํ์ฌ ์คํฌ๋กค ์์น๋ก ์ค์ ํด `overflow-y:scroll,width:100%`๋ฅผ ํตํด ์คํฌ๋กค ๋ฐฉ์ง๊ฐ ๋๋ ์ฝ๋์ด๋ค.
ํ์ง๋ง ๋ด ์ฝ๋์์๋ modal์ฐฝ์ด ๋จ์ง ์์ ์ํ์์๋ fixed๊ฐ ๋์ด๋ฒ๋ฆฌ๋ ํ์์ ๊ฒช์๋ค.
//๋ฌ์ฑ๋ฅ ๊ณผ ๋์ ์ธ์ฆ์ท ๋ณด์ฌ์ฃผ๋ ํญ
function Achievement() {
const [Modal, setModal] = useState(false)
useEffect(() => {
if (Modal === false) {
console.log('bye', Modal)
} else {
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);
console.log('hi', Modal)
};
}
}, [Modal]);
return (
<>
<CertifyGoBtn hColor={'#65ACE2'} dColor={'#98C064'} onClick={() => setModal(true)}>์ธ์ฆํ๊ธฐ</CertifyGoBtn>
<MissionModal show={Modal} setShow={setModal} />
</>
)
}
๋๋ `์ธ์ฆํ๊ธฐ` ๋ฒํผ์ ํด๋ฆญ ์ useState๋ฅผ ํตํด Modal์ด๋ผ๋ ๊ฐ์ ๋ฐ๊พธ์ด ์ฃผ์๋ค. useEffect๊ฐ Modal์ด๋ผ๋ ๊ฐ์ ์ถ์ ํ ์ ์๊ฒ` [Modal]`์ ์ ์ฉํ๋ค. ๋ฐ๋ผ์ useEffectModal์ ๊ฐ์ด true์ผ ๋๋ง ์คํฌ๋กค์ด ๋ฉ์ถ๊ฒ ํ๋ค.
์ฐธ๊ณ ํ site
'Development > React.js' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
SPA / CSR / TTI / TTV / SEO / Metaํ๊ทธ / Opengraph (0) | 2022.10.14 |
---|---|
์ํฐ๋ ํ๋ฆฌ์จ๋ณด๋ฉ ์ฑ๋ฆฐ์ง ์ฌ์ ๊ณผ์ (CSR / SSR with Next.js) (0) | 2022.09.28 |
๋ ธ๋ง๋์ฝ๋ React JS ํด๋์ค #3 typescript (0) | 2022.06.29 |
๋ ธ๋ง๋์ฝ๋ React JS ํด๋์ค #2 styled components - log (0) | 2022.06.28 |
[nomadcoders_React.js]ToDoApp (0) | 2022.06.21 |
๋๊ธ