Header 동적으로 변경

2025. 1. 21. 00:56· 카테고리 없음
목차
  1. 쿠키 설정 방법
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";

 

저작자표시 (새창열림)
  1. 쿠키 설정 방법
유민기
유민기
유민기
Youminki
유민기
전체
오늘
어제
  • 분류 전체보기 (45)
    • 백준 : BFS (5)
    • 알고리즘(이충기 교수) (4)
    • 웹해킹 (6)
    • 백준 : 동적 프로그래밍 (11)
    • 백준 : 분할정복 (5)
    • 백준 : backtraking (2)
    • 컴퓨터 보안(한승철 교수) (4)
    • FrontEnd (4)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

태그

최근 댓글

최근 글

hELLO · Designed By 정상우.v4.2.0
유민기
Header 동적으로 변경
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.