본문 바로가기

Frontend

[Storybook] 라이트모드, 다크모드 토글 기능 추가하기

개요

  • 회사에서 디자인 시스템을 업데이트 하면서 새로 추가된 다크모드, 라이트모드 기능을 스토리북에서도 테스트해보고 싶다.
  • 스토리북에서 다크모드, 라이트모드에 따라 컴포넌트 스타일이 변화되는 것을 눈으로 확인해보자.

방법

  1. 애드온 설치

우선 스토리북에서 theme을 사용하기 위해 애드온을 설치한다.

npm i -D @storybook/addon-themes
  1. main.ts 파일 환경설정
// .storybook/main.ts
export default {
  addons: ['@storybook/addon-themes'],
};
  • main.ts 파일에 addons에 설치한 라이브러리를 등록한다.
  1. preview.tsx 파일 환경설정
import { withThemeByClassName } from '@storybook/addon-themes';
import type { Preview, ReactRenderer } from '@storybook/react';
import '../src/styles/global.scss';

const setHtmlDataTheme = (theme: string) => {
  document.documentElement.setAttribute('data-theme', theme);
};

const preview: Preview = {
  ...
  decorators: [
    (Story, context) => {
      const theme = context.globals.theme || 'light';
      setHtmlDataTheme(theme);
      return <Story {...context} />;
    },
    withThemeByClassName<ReactRenderer>({
      themes: {
        light: 'light',
        dark: 'dark',
      },
      defaultTheme: 'light',
    }),
  ],
};
  • decorators에 html 태그에 data-theme 속성값에 따라 global.scss 파일에서 다크모드, 라이트모드 색상을 구분해서 적용해주는 로직을 담아준다.