[React] Storybook 사용해보기

2022. 12. 2. 02:11·FE/React
반응형

프로젝트 세팅

https://storybook.js.org/tutorials/intro-to-storybook/react/ko/get-started/

 

Storybook Tutorials

Learn how to develop UIs with components and design systems. Our in-depth frontend guides are created by Storybook maintainers and peer-reviewed by the open source community.

storybook.js.org

 

스토리북을 기존 프로젝트에 추가하려면 아래 커맨드를 터미널에 입력해주면 된다.

npx storybook init

 

설치가 끝나면 자동으로 기본 세팅이 되어있는 것을 확인할 수 있다

 

아래 명령어를 통해 스토리북을 실행해볼 수 있다.

yarn storybook

 

introduction

 

기본적으로 만들어져있는 컴포넌트 확인

 


 

컴포넌트 만들기

src/components/Button/index.tsx

import { ReactNode } from 'react'
import cx from 'classnames'

import styles from './button.module.scss'

interface Props {
  children: ReactNode
  size: 'large' | 'small'
  primary?: boolean
}

export const Button = ({ children, size, primary }: Props) => {
  return (
    <button type='button' className={cx(styles.button, styles[size], { [styles.primary]: primary })}>
      {children}
    </button>
  )
}

간단하게 버튼의 텍스트 내용, 사이즈, primary 여부를 props으로 받아서 버튼 컴포넌트를 만들어주었다.

 

src/components/Button/button.module.scss

@use 'src/styles/constants/colors';

.button {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid colors.$GRAYA;

  + .button {
    margin-left: 14px;
  }

  &.primary {
    color: colors.$WHITE;
    background-color: colors.$BLUE !important;
    border-color: transparent;
  }

  &.small {
    height: 24px;
    padding: 0 12px;
    font-size: 12px;
    border-radius: 5px;
  }

  &.large {
    height: 40px;
    padding: 0 24px;
    font-size: 14px;
    border-radius: 10px;
  }
}

 

 

스토리 작성

미리 만들어져있던 스토리들은 삭제해주고, 새로운 스토리를 만들어준다.

src/stories/Button.stories.tsx

import { ComponentStory, ComponentMeta } from '@storybook/react'

import '../styles/index.scss'
import { Button } from 'components'

export default {
  title: 'Example/Button', // Example 카테고리 안에 Button title이 생긴다.
  component: Button,
} as ComponentMeta<typeof Button>

const Template: ComponentStory<typeof Button> = (args) => <Button {...args} />

// 새로운 스토리 생성
export const ButtonTemplate = Template.bind({})

// <Button size='large' primary>Button</Button> 과 같음
ButtonTemplate.args = {
  primary: true,
  size: 'large',
  children: 'Button',
}

위에서 만들었던 Button 컴포넌트를 import해주고 어떤 컴포넌트의 스토리인지 정의해준다.

그리고 bind를 통해 새로운 스토리들을 생성해주면 된다.

 

 

 

다크모드 적용

add-on을 사용하면 스토리북에서 제공하는 추가 기능들을 이용할 수 있다. 이를 이용해 다크모드에서도 테스트해볼 수 있도록 해보자.

 

먼저 아래 커맨드를 통해 storybook-dark-mode를 추가해준다.

yarn add -D storybook-dark-mode

// or

npm install --save-dev storybook-dark-mode

 

src/components/Button/button.module.scss

@use 'src/styles/constants/colors';

.button {
  transition: all 300ms;

  // ...
  
  :root[color-theme='dark'] & {
    color: colors.$WHITE;
    background-color: colors.$GRAY3;
    border-color: colors.$GRAY3;
  }
}

기존의 컴포넌트 스타일에 다크모드일 때 스타일을 추가해준다.

 

해당 방법으로 다크모드를 구현하는 방법은 아래의 글에 자세히 정리해놓았다.

https://doooodle932.tistory.com/123

 

React 다크 모드 구현하기(with Recoil, SCSS)

React에서 간단하게 다크 모드를 구현해보려고 한다. 폴더 구조 ├─assets │ └─svgs ├─routes │ ├─Home │ ├─Weather │ └─_shared │ └─GNB ├─states └─types 테마 구분 states/theme.ts import { ato

doooodle932.tistory.com

 

.storybook/main.js

module.exports = {
  addons: [
    // ...
    'storybook-dark-mode',
  ],
}

먼저 .storybook의 main.js 파일의 addons 부분에 storybook-dark-mode를 추가해준다.

 

애드온을 추가해주면 위처럼 dark/light 모드 토글 버튼이 생긴다.

 

.storybook/preview.js

import { useDarkMode } from 'storybook-dark-mode'

export const decorators = [
  (Story) => {
    document.documentElement.setAttribute('color-theme', useDarkMode() ? 'dark' : 'light')

    return <Story />
  },
]

 

useDarkMode를 사용하면 현재 다크모드인지 아닌지를 확인할 수 있다. 이를 통해 현재 theme을 알아내 attribute를 설정해주는 방식으로 하면 다크모드에 맞게 컴포넌트 스타일이 바뀌도록 할 수 있다.

(emotion이나 styled-components같은 CSS-in-JS를 사용하는 경우 theme값을 넘겨준 ThemeProvider로 Story를 감싸주는 방식으로 다크모드를 구현할 수도 있다.)

 

 

References

https://storybook.js.org/addons/storybook-dark-mode

https://davidyeiser.com/tutorials/storybook-react-with-dark-mode#7-connect-the-react-components-to-the-storybook-dark-mode-control

 

반응형

'FE > React' 카테고리의 다른 글

[React] 재귀 컴포넌트로 트리 메뉴 만들기(2)  (0) 2022.12.26
[React] 재귀 컴포넌트로 트리 메뉴 만들기(1)  (0) 2022.12.20
React Infinite Carousel 만들기(TS)  (1) 2022.11.24
React 스톱워치 구현하기(TS)  (0) 2022.11.17
React 다크 모드 구현하기(with Recoil, SCSS)  (0) 2022.11.06
'FE/React' 카테고리의 다른 글
  • [React] 재귀 컴포넌트로 트리 메뉴 만들기(2)
  • [React] 재귀 컴포넌트로 트리 메뉴 만들기(1)
  • React Infinite Carousel 만들기(TS)
  • React 스톱워치 구현하기(TS)
SH_Roh
SH_Roh
  • SH_Roh
    혼자공부끄적끄적
    SH_Roh
  • 전체
    오늘
    어제
    • 분류 전체보기 (159)
      • FE (39)
        • HTML, CSS (3)
        • Javascript (17)
        • React (11)
        • Next.js (4)
      • Network (1)
      • DevOps (4)
      • Git (1)
      • Trouble Shooting (24)
      • Algorithm (41)
        • Python (2)
        • Data Structure, Algorithm (7)
        • Problem Solving (31)
      • Education (23)
        • Elice AI Track (4)
        • Wanted Pre-Onboarding FE Co.. (19)
      • TIL (25)
      • Etc. (1)
        • 회고 (1)
        • 그냥저냥 (0)
  • 링크

    • Github
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
SH_Roh
[React] Storybook 사용해보기
상단으로

티스토리툴바