728x90
๋ฐ์ํ
๐์คํฌ๋กค ์ ๋ ๊ฐ์ด๋ ๊ตฌํ
"use client";
import { useState, useEffect, useRef } from "react";
import gsap from "gsap";
export default function page() {
const [isSpecialCase, setIsSpecialCase] = useState(false);
const handleScrollGuideClick = () => {
if (isSpecialCase) {
window.scrollTo({
top: 0,
behavior: "smooth", //์คํฌ๋กค ๋ถ๋๋ฝ๊ฒ
});
}
};
useEffect(() => {
const handleScroll = () => {
const isScrollAtBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight;
const scrollTop = window.scrollY;
// ์๋จ์ผ๋ก ์คํฌ๋กค๋ ๋์ ์กฐ๊ฑด์ ์ค์ (์: 0 ๋๋ ์ํ๋ ๊ฐ)
const isTop = scrollTop === 0;
if (isScrollAtBottom) {
setIsSpecialCase(!isSpecialCase);
} else if (isTop) {
setIsSpecialCase(isSpecialCase);
}
};
document.addEventListener("scroll", handleScroll);
// Clean up the event listener on component unmount
return () => {
document.removeEventListener("scroll", handleScroll);
};
}, []); // Empty dependency array to run the effect only once on mount
return (
<>
{/* ์คํฌ๋กค ์ ๋ ๊ฐ์ด๋ */}
<div
className={`${isSpecialCase ? "scroll_guide_up" : "scroll_guide"}`}
onClick={handleScrollGuideClick}
>
<span></span>
<span></span>
<span></span>
</div>
</>
);
}
[isSpecialCase, setIsSpecialCase] = useState(false)
- isSpecialCase: ์คํฌ๋กค์ด ํ์ด์ง ๋งจ ์๋๋ก ๋๋ฌํ๋ฉด true๊ฐ ๋๋ ์ํ์ด๋ค.
- setIsSpecialCase: isSpecialCase ์ํ๋ฅผ ์ ๋ฐ์ดํธํ๋ ํจ์์ด๋ค.
handleScrollGuideClick()
- handleScrollGuideClick ํจ์๋ ์คํฌ๋กค ๊ฐ์ด๋๊ฐ ํด๋ฆญ๋์์ ๋ ํธ์ถ๋๋ค.
- isSpecialCase๊ฐ true์ผ ๋ (์คํฌ๋กค์ด ๋งจ ์๋๋ก ๋๋ฌํ ๊ฒฝ์ฐ), ํ์ด์ง๋ฅผ ๋งจ ์๋ก ๋ถ๋๋ฝ๊ฒ ์คํฌ๋กคํ๋ค.
- window.scrollTo๋ฅผ ์ฌ์ฉํ์ฌ ํ์ด์ง๋ฅผ ๋งจ ์๋ก ์คํฌ๋กคํ๊ณ , behavior: "smooth"๋ฅผ ํตํด ๋ถ๋๋ฌ์ด ์คํฌ๋กค ํจ๊ณผ๋ฅผ ์ ์ฉํ๋ค.
handleScroll()
const isScrollAtBottom = window.innerHeight + window.scrollY >= document.body.offsetHeight
- ํ์ฌ ๋ทฐํฌํธ์ ๋งจ ์๋ ์์น๋ฅผ ์๋ฏธํ๋ฉฐ, document.body.offsetHeight๋ ํ์ด์ง์ ์ด ๋์ด๋ฅผ ๋ํ๋ธ๋ค.
- ๋ฐ๋ผ์ ์ด ์กฐ๊ฑด์ด true์ด๋ฉด ํ์ด์ง๊ฐ ๋งจ ์๋๋ก ์คํฌ๋กค๋์๋ค๋ ๊ฒ์ ๋ํ๋ธ๋ค.
- window.innerHeight๋ ํ์ฌ ๋ทฐํฌํธ(ํ๋ฉด์ ๋ณด์ด๋ ์์ญ)์ ๋์ด๋ฅผ ๋ํ๋ธ๋ค.
- ์ด ๊ฐ์ ์ฌ์ฉ์์ ๋ธ๋ผ์ฐ์ ์ฐฝ์ ํ์๋๋ ๋ด์ฉ ์์ญ์ ์ธ๋ก ๋์ด๋ฅผ ์๋ฏธํ๋ค.
const scrollTop = window.scrollY;
- window.scrollY๋ ํ์ฌ ์ธ๋ก ์คํฌ๋กค ์์น๋ฅผ ๋ํ๋ธ๋ค.
- ์ฌ์ฉ์๊ฐ ํ์ด์ง๋ฅผ ์ธ๋ก๋ก ์คํฌ๋กคํ ๋๋ง๋ค ๊ฐ์ด ์ฆ๊ฐํ๋ฉฐ, ํ์ด์ง์ ๋งจ ์์์๋ถํฐ ํ์ฌ ์คํฌ๋กค ์์น๊น์ง์ ์ธ๋ก ๊ฑฐ๋ฆฌ๋ฅผ ๋ํ๋ธ๋ค. ์ฌ์ฉ์๊ฐ ํ์ด์ง๋ฅผ ์คํฌ๋กคํ๊ธฐ ์ ๊น์ง๋ 0์ด๋ค.
className={`${isSpecialCase ? "scroll_guide_up" : "scroll_guide"}`}
- isSpecialCase๊ฐ true์ผ ๋ (์คํฌ๋กค์ด ๋งจ ์๋๋ก ๋๋ฌํ ๊ฒฝ์ฐ), scroll_guide_up์ผ๋ก className์ ์ค์ ํด์ ๊ธฐ๋ฅ์ ๋ง๋ ๋์์ธ์ ํด์ค๋ค.
๐์คํฌ๋กค ์ ๋ ๊ฐ์ด๋ ์ต์ข ๊ตฌํ ์์
728x90
๋ฐ์ํ
'Frontend > Next.js' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Next.js - Data fetching (React vs Next.js) (0) | 2024.02.11 |
---|---|
Next.js 14๋ฒ์ - Layouts,Metadata,Dynamic Routes (0) | 2024.02.08 |
Next.js - ๊ฐ๋ก ์คํฌ๋กค ๋ฐ ๊ตฌํ (0) | 2023.12.19 |
Next.js - modal ์ฐฝ ๋ง๋ค๊ธฐ (0) | 2023.12.19 |
Next.js 14๋ฒ์ - favicon ๋ฐ๊พธ๊ธฐ (1) | 2023.11.10 |