NextJS Sticky Header 만들기

루비·2023년 6월 17일
0

NextJS

목록 보기
6/7
import React, { useState, useEffect, useRef } from "react";
import { useRouter } from "next/router";

const Header = () => {
  const menu = ["Home", "Service", "Solution", "FAQ"];
  const router = useRouter();

  const headerRef = useRef(null);
  const [isHeaderDropped, setIsHeaderDropped] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      const headerElement = headerRef.current;
      if (headerElement) {
        const headerHeight = headerRef.current.offsetHeight;
        const windowTop = window.scrollY;

        if (windowTop >= headerHeight) setIsHeaderDropped(true);
        else setIsHeaderDropped(false);
      }
    };

    window.addEventListener("scroll", handleScroll);
    // 창 크기가 조정 될 때마다 실행됨 헤더 크기가 조정될 때 실행됨.
    window.addEventListener("resize", handleScroll);

    return () => {
      window.removeEventListener("scroll", handleScroll);
      window.removeEventListener("resize", handleScroll);
    };
  }, []);

  return (
    <div
      className={`headerContainer ${isHeaderDropped ? "drop" : ""}`}
      ref={headerRef}>
      <nav className="header">
        <div className="">Logo</div>
        <ul>
          {menu.map((menuItem) => (
            <li key={menuItem} onClick={() => router.push("/")}>
              {menuItem}
            </li>
          ))}
        </ul>
      </nav>
    </div>
  );
};

export default Header;
profile
개발훠훠

0개의 댓글