- Published on
스크롤 올리면 다시 보이는 Navbar
- Authors
- Name
- Inhwan Cho
Navbar.tsx
import React, { useState, useEffect } from 'react';
// 스로틀(throttle) 대신 useEffect를 사용해도 됩니다.- 여기에선 효율을 위해 스로틀을 사용.
function throttleHelper(callback: () => void, waitTime: number): () => void {
let timerId: ReturnType<typeof setTimeout> | null = null;
return function () {
if (timerId === null) {
timerId = setTimeout(() => {
callback();
timerId = null;
}, waitTime);
}
};
}
const Navbar = () => {
const [prevScrollPos, setPrevScrollPos] = useState(0);
const [isVisible, setIsVisible] = useState(true);
const [searchBtn, setSearchBtn] = useState(false);
const handleScroll = throttleHelper(() => {
const currentScrollPos = window.scrollY;
const isScrollingUp = prevScrollPos > currentScrollPos;
setIsVisible(isScrollingUp || currentScrollPos < 10);
setPrevScrollPos(currentScrollPos);
}, 100);
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, [prevScrollPos, isVisible, handleScroll]);
return (
<header
className={`sticky top-0 w-full bg-zinc-200 dark:bg-zinc-900 z-10 transition-transform duration-300
${isVisible ? '-translate-y-full' : 'translate-y-0'}`}
>
Hello World
</header>
);
};
export default Navbar;
- 옵션을
isVisible ? "top-0" : "top-[-65px]"
처럼 top을 주거나 또는 위의 예시처럼 translate-y 옵션으로 설정