๋๋ถ๋ถ์คํฌ๋กค ๋ฐฉํฅ์ ๋ฐ์ํ๋ ํค๋์์ ์ฐธ๊ณ ํด์ ์์ฑํ์ต๋๋ค.
์คํฌ๋กค์ ์๋๋ก ๋ด๋ฆฌ๋ฉด ํค๋๊ฐ ์ฌ๋ผ์ง๊ณ ์๋ก ์ฌ๋ฆฌ๋ฉด ํค๋๊ฐ ๋ํ๋๋๋ก ๊ตฌํํ๋ ๋ฐฉ๋ฒ์ ๋ํ ํฌ์คํธ์ ๋๋ค.
// 2022/05/11 - ์ค๋กํ ํฌํผ ํจ์ - by 1-blue
export const throttleHelper = (callback: () => void, waitTime: number) => {
let timerId: ReturnType<typeof setTimeout> | null = null;
return () => {
if (timerId) return;
timerId = setTimeout(() => {
callback();
timerId = null;
}, waitTime);
};
};
// 2022/05/11 - ํค๋ ์จ๊น ์ฌ๋ถ ๋ณ์ - by 1-blue
const [hide, setHide] = useState(false);
// 2022/05/11 - ํ์ฌ ์คํฌ๋กค ์์น๊ฐ ์ ์ฅํ ๋ณ์ - by 1-blue
const [pageY, setPageY] = useState(0);
// 2022/05/11 - ํ์ฌ ์คํฌ๋กค์ ๋ด๋ ธ๋์ง ์ฌ๋ ธ๋์ง ํ์ธํ ์คํฌ๋กค ์ด๋ฒคํธ ํจ์ - by 1-blue
const handleScroll = () => {
const { pageYOffset } = window;
const deltaY = pageYOffset - pageY;
const hide = pageYOffset !== 0 && deltaY >= 0;
setHide(hide);
setPageY(pageYOffset);
};
// 2022/05/11 - ์คํฌ๋กค ์ด๋ฒคํธ์ ์ค๋กํ๋ง ์ ์ฉ - by 1-blue
const throttleScroll = throttleHelper(handleScroll, 50);
// 2022/05/11 - ์คํฌ๋กค ์ด๋ฒคํธ ๋ฑ๋ก - by 1-blue
useEffect(() => {
document.addEventListener("scroll", throttleScroll);
return () => document.removeEventListener("scroll", throttleScroll);
}, [throttleScroll]);
// jsx ( tailwindCss ์ฌ์ฉ )
<header
className={combineClassNames(
"sticky top-0 w-full bg-zinc-200 dark:bg-zinc-900 z-10 transition-transform duration-300",
hide ? "-translate-y-20" : "translate-y-0"
)}
>
// ๋ด๋ถ ์๋ต...
</header>
๋์์ด ๋์์ต๋๋ค ์ ๋ง ๊ฐ์ฌํฉ๋๋ค!!