카테고리 없음

Header 동적으로 변경

유민기 2025. 1. 21. 00:56
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import styled from "styled-components";
import Cookies from "js-cookie";

import Alarm from "../assets/Home/Alarm.svg";
import BasketIcon from "../assets/Home/Basket.svg";
import MypageIcon from "../assets/Home/Mypage.svg";
import Logo from "../assets/Logo.svg";

const Header: React.FC = () => {
  const navigate = useNavigate();
  const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);
  const [nickname, setNickname] = useState<string>("");

  useEffect(() => {
    // 쿠키에서 로그인 상태 확인
    const userNickname = Cookies.get("nickname"); // "nickname" 쿠키 가져오기
    if (userNickname) {
      setIsLoggedIn(true);
      setNickname(userNickname); // 닉네임 설정
    } else {
      setIsLoggedIn(false);
    }
  }, []);

  const handleMypageClick = () => {
    navigate("/login"); // /login 페이지로 이동
  };

  const handleBasketClick = () => {
    navigate("/basket"); // /basket 페이지로 이동
  };

  return (
    <HeaderWrapper>
      <HeaderContainer>
        {/* 왼쪽 섹션 */}
        <LeftSection>
          {isLoggedIn ? (
            <Greeting>
              <ProfileImage
                src="https://via.placeholder.com/44"
                alt="User profile"
              />
              <GreetingText>
                <span>{nickname}</span> 님 안녕하세요!
              </GreetingText>
            </Greeting>
          ) : (
            <LogoIcon src={Logo} alt="Logo" />
          )}
        </LeftSection>

        {/* 오른쪽 섹션 */}
        <RightSection>
          {isLoggedIn ? (
            <>
              <Icon
                src={BasketIcon}
                alt="Basket"
                onClick={handleBasketClick} // 장바구니 클릭 시 이동
              />
              <Icon src={Alarm} alt="알림" />
            </>
          ) : (
            <>
              <Icon
                src={MypageIcon}
                alt="마이페이지"
                onClick={handleMypageClick} // 마이페이지 클릭 시 이동
              />
              <Icon src={Alarm} alt="알림" />
            </>
          )}
        </RightSection>
      </HeaderContainer>
    </HeaderWrapper>
  );
};

export default Header;

const HeaderWrapper = styled.div`
  min-width: 340px;
  background-color: #e60000;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  max-width: 1280px;
  margin: 0 auto;
  padding: 1rem;
  text-align: center;
  z-index: 1000;
`;

const HeaderContainer = styled.header`
  display: flex;
  justify-content: space-between;
  align-items: center;
`;

const LeftSection = styled.div`
  display: flex;
  align-items: center;
`;

const RightSection = styled.div`
  display: flex;
  align-items: center;
  gap: 15px;
`;

const ProfileImage = styled.img`
  width: 44px;
  height: 44px;
  border-radius: 50%;
  margin-right: 10px;
`;

const Greeting = styled.div`
  display: flex;
  align-items: center;
`;

const GreetingText = styled.span`
  font-family: "NanumSquare Neo OTF", sans-serif;
  font-style: normal;
  color: #ffffff;
  font-weight: 500;
  font-size: 18px;

  & > span {
    font-weight: 700;
    margin-right: 5px;
  }
`;

const LogoIcon = styled.img`
  width: auto;
  height: auto;
`;

const Icon = styled.img`
  width: auto;
  height: auto;
  cursor: pointer;
`;

Header를 로그인 | 비로그인 상태에 따라 동적으로 변하도록 설정하고 로컬환경에서 테스트하기

- 로그인시 들어갈 아이콘, 비로그인시 들어갈 아이콘을 셋팅한다

- 쿠키값을 nickname을 통해 로그인 상태를 확인할 수 있도록 만들어준다.

-직접 로그인하지 않아도 콘솔에서 쿠키 설정을 통해 로그인 | 비로그인 헤더를 구축해볼 수 있다

쿠키 설정 방법

1) 로그인 상태 테스트:

브라우저의 개발자 도구 콘솔에서 아래 명령어로 쿠키를 설정:

document.cookie = "nickname=Youminki; path=/; max-age=3600";​
  • nickname=JohnDoe: 사용자 닉네임 설정.
  • path=/: 쿠키가 사이트의 모든 경로에서 유효하도록 설정.
  • max-age=3600: 쿠키가 1시간 동안 유효.

2) 로그아웃 상태 테스트:

브라우저 콘솔에서 아래 명령어로 쿠키를 삭제:

document.cookie = "nickname=; path=/; max-age=0";