[React] 다크&라이트 모드 적용하기 (With. Styled-components, Theme, atom, globalStyle)

hellow_coding·2023년 6월 5일

1. "styled-components"의 "DefaultTheme"

테마를 사용하는 경우, TypeScript가 테마의 타입을 알 수 있도록 해야 합니다. 이를 위해 보통 별도의 타입 정의 파일을 만들고, 이 파일에서 DefaultTheme을 확장합니다.

// styled.d.ts

import "styled-components";

// "DefaultTheme"으로 테마 정의를 확장
declare module "styled-components" {
  export interface DefaultTheme {
    // 테마에 대한 추가 타입 정의
    textColor: string;
    bgColor: string;
    accentColor: string;
  }
}

: DefaultTheme이라는 인터페이스를 확장하여 bgColor, textColor, accentColor라는 프로퍼티를 추가

declare module은 기존 JavaScript 모듈에 대한 타입 선언을 추가하거나 변경할 때 사용하는 키워드입니다.


2. 프로퍼티 값 지정

// theme.ts

import { DefaultTheme } from "styled-components";

export const darkTheme: DefaultTheme = {
  bgColor: "#a29bfe",
  textColor: "black",
  accentColor: "#e17055",
};

export const lightTheme: DefaultTheme = {
  bgColor: "whitesmoke",
  textColor: "black",
  accentColor: "#e17055",
};

: 타입을 지정하고 프로퍼티에 값을 지정

DefaultTheme으로 타입을 지정하고 프로퍼티에 값을 지정한다는 것은, 우리가 정의하는 테마 객체가 일정한 구조를 가지고, 그 구조에 따라 값을 가지도록 한다는 뜻입니다. 이를 통해 애플리케이션의 스타일을 일관성 있게 유지할 수 있습니다.


3. Recoil에서 atom (상태관리)

npm install recoil

atomRecoil의 기본 상태 단위로, 상태의 일부를 나타내는 값과 그 값을 변경하는 방법으로 구성됩니다. 각 atom은 고유한 키를 가지며, 이 키를 통해 컴포넌트에서 atom에 접근하고 해당 값을 사용하거나 변경할 수 있습니다.

// atom.ts

import { atom } from "recoil";

export const isDarkAtom = atom({
  key: "isDark", // 유니크한 ID(다른 atom/selector와 관련하여)
  default: false, // 기본값 (초기값)
});
profile
꿈많은 개발자

0개의 댓글