본문 바로가기
Recap/bookshelf

[8일차] 프로젝트 끝! 다크모드, 페이지 상단으로 이동하기

by yerin.dev 2024. 1. 31.

오늘 한 일

 

  1. 다크모드 구현
    사이트에 접속했을 때 사용자의 설정 prefers-color-scheme에 따라서 테마를 다르게 보여준다. 만약 localStorage에 저장된 값이 있으면 참조한다. 아니면, 기본적으로 밝은 테마(emerald)를 보여주고, localStorage에도 저장한다. 그리고 useRecoilState로 전역 관리하고 있는 상태 theme에 테마 이름을 할당한다.

 

// App.tsx

useEffect(() => {
    if (
      window.matchMedia("(prefers-color-scheme: dark)").matches ||
      localStorage.getItem("theme") == "dracula"
    ) {
      document.documentElement.setAttribute("data-theme", "dracula");
      setTheme("dracula");
    } else {
      document.documentElement.setAttribute("data-theme", "emerald");
      localStorage.setItem("theme", "emerald");
      setTheme("emerald");
    }
  }, []);

 

 

그리고 버튼 컴포넌트에서는, 버튼을 클릭하면 테마를 맞게 설정하고 localStorage에도 저장한다. 그리고 테마가 바뀔 때마다 html의 data-theme attribute도 바뀐다.

 

 

// DarkModeBtn.tsx
useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
  }, [theme]);

<button
      onClick={() => {
        if (theme == "emerald") {
          setTheme("dracula");
          localStorage.setItem("theme", "dracula");
        } else {
          setTheme("emerald");
          localStorage.setItem("theme", "emerald");
        }
      }}
    >
      {theme == "emerald" && <MdSunny />}
      {theme == "dracula" && <IoMdMoon />}
</button>

 

 

daisyUI 사용하지 않았다면 css에서 .html[data-theme="dark"]와 .html[data-theme="light"] (혹은 body에 설정해도 됨) 에 color, backgroundColor 등 css 변수를 알맞게 주면 될 듯 하다. daisyUI 덕분에 간편하게 끝났지만.

 

 

  1. 페이지 상단으로 이동하기 버튼
<button
      onClick={() => {
        window.scrollTo({
          top: 0,
          behavior: "smooth",
        });
      }}
    >
    up!
    </button>

 

 

느낀 점

 

 

프로젝트 시작하기 전에 구현해야겠다고 생각한 기능들은 얼추 구현했다.
남은 것은 로그인 기능 리팩토링하기(Firebase를 벗어나 그냥 구현해야 할까 싶다.) 그리고 나머지 코드들 리팩토링 하기 정도인데
이건 지금 당장 하기보다는 천천히 공부해가면서 리팩토링할 예정이라, 1차 마무리를 여기서 해야할 것 같다.
정말 0에서부터 시작한 프로젝트는 이게 진짜 처음이었는데 내가 예전부터 진짜 있었으면 좋겠다고 생각한 기능(책장 태그로 정리)이 구현된 사이트를 내가 내 손으로 만들다니 정말 감격스럽고 이걸 사실 일주일 만에 했다는 것도 놀랍다. 👏
하기 전에는 분명 2주 넘게 걸릴 것이라고 생각해서... 허허. 아무튼 마무리는 여기서 하고 사이트는 차차 업그레이드 해가야겠다.