반응형
스크롤시 상단 메뉴바 숨기기
작동화면
Code
NavBar.tsx
import { useScrollDirection } from "./useScrollDirection";
import styled from "styled-components";
const Header = styled.div`
position: sticky;
height: 3rem;
transition-property: all;
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
transition-duration: 500ms;
`;
const HeaderDown = styled.div`
top: -3rem;
`;
const NavBar = () => {
const scrollDirection = useScrollDirection();
return (
<>
{scrollDirection === "down" && (
<HeaderDown>
// ...
</HeaderDown>
)}
{scrollDirection !== "down" && (
<Header>
//...
</Header>
)}
</>
);
};
export default NavBar;
useScrollDirection.tsx
import { useEffect, useState } from "react";
export function useScrollDirection() {
const [scrollDirection, setScrollDirection] = useState("");
useEffect(() => {
let lastScrollY = window.pageYOffset;
const updateScrollDirection = () => {
const scrollY = window.pageYOffset;
const direction = scrollY > lastScrollY ? "down" : "up";
if (
direction !== scrollDirection &&
(scrollY - lastScrollY > 10 || scrollY - lastScrollY < -10)
) {
setScrollDirection(direction);
}
lastScrollY = scrollY > 0 ? scrollY : 0;
};
window.addEventListener("scroll", updateScrollDirection); // add event listener
return () => {
window.removeEventListener("scroll", updateScrollDirection); // clean up
};
}, [scrollDirection]);
return scrollDirection;
}
RootComponent.tsx
import NavBar from "../components/navbar/NavBar";
const HideNavBar = () => {
return (
<>
<NavBar />
<div>
<h1>상단 메뉴바 숨기기</h1>
{Array.from({ length: 60 }).map(function (u, i) {
return (
<p key={i}>
스크롤을 내릴때는 메뉴바가 사라지고 스크롤을 올릴때는 메뉴바가
보입니다.
</p>
);
})}
</div>
</>
);
};
export default HideNavBar;
반응형
'Study > React' 카테고리의 다른 글
Next.js ) Input 입력값 태그로 변환하기 (TypeScript) (0) | 2022.07.15 |
---|---|
React ) redux-saga 기반 api 호출 연습 (1) | 2022.05.11 |
React ) Recoil 로 Axios 비동기 처리하기 (0) | 2022.05.10 |
React ) HackerNews WebApp 제작을 통한 React 학습 (0) | 2022.05.07 |
React ) Class 형 보다 Hook(함수) 형을 권장하는 이유 (0) | 2022.05.06 |
댓글