Storybook 기능 소개 2탄

제이든·2022년 2월 10일
0

1. args

이전 챕터까지는 다음과 같은 방식으로 props를 inline(?) 방식으로 전달해주면서 스토리를 작성했었다.

export const Primary = () => <Button variant="primary">Primary</Button>;

이제는 args를 이용해서 스토리를 작성하는 방법을 알아보자. 먼저 템플릿을 작성해보자.

Button.stories.js

const Template = (args) => <Button {...args} />;

이후에 Primary 컴포넌트 스토리를 Template을 이용해서 작성해보자.

export const PrimaryA = Template.bind({});

PrimaryA.args = {
  variant: 'primary',
  children: 'Primary Args',
};

우리가 생각한 대로 스토리가 추가된 것을 확인할 수 있다.

그런데 왜 이렇게 작성하는거지?

1. props를 전달하는 것을 좀 더 직관적으로 보여줄 수 있다.
2. 이렇게 작성하면 args를 재사용할 수 있기 때문에 중복된 코드를 줄일 수 있다.

재사용해보자!

export const LongPrimaryA = Template.bind({});
LongPrimaryA.args = {
  ...PrimaryA.args,
  children: 'Long Primary Args',
};

export default 에 공통적으로 기본 값을 설정해줄 수도 있다.

export default {
  title: 'Form/Button',
  component: Button,
  args: {
    children: 'button',
  },
};

args의 children은 스토리 레벨에서 작성이 되어 있으면 오버라이딩된다.

2. decorators

데코레이터는 보통 래핑 컴포넌트에 많이 사용된다. 바로 사용해보면서 알아보자.

지금까지 만든 버튼 컴포넌트를 가운데로 이동해서 보여주고 싶다고 해보자.

center 폴더를 만들자.
Center.js

import React from 'react';
import './Center.css';

const Center = (props) => {
  return <div className="center">{props.children}</div>;
};

export default Center;

Center.css

.center {
  display: flex;
  justify-content: center;
}

그리고 마지막으로 Button.stories.js의 스토리들을 모두 Center컴포넌트로 감싸주자.

export const Primary = () => (
  <Center>
    <Button variant="primary">Primary</Button>
  </Center>
);
export const Secondary = () => (
  <Center>
    <Button variant="secondary">Secondary</Button>
  </Center>
);
export const Success = () => (
  <Center>
    <Button variant="success">Success</Button>
  </Center>
);
export const Danger = () => (
  <Center>
    <Button variant="danger">Danger</Button>
  </Center>
);

center 정렬이 된 것으로 확인된다. 이렇게 Center 컴포넌트로 감싸서 정렬시켰는데 여기서 Center컴포넌트가 데코레이터라고 할 수 있겠다.

하지만 이렇게 매번 감싸준다면 불편할 것이다. 따라서 데코레이터로서 사용해보자.

Button.stories.js

export default {
  title: 'Form/Button',
  component: Button,
  decorators: [(story) => <Center>{story()}</Center>],
};

아까와 같은 효과를 기대할 수 있다.

만약에 전역에 데코레이터를 모든 컴포넌트에 추가해주고 싶다면 /.storybook/preview.js에 다음과 같이 추가하면 된다.

import { addDecorator } from '@storybook/react';
import Center from '../src/components/Center/Center';

addDecorator((story) => <Center>{story()}</Center>);

profile
개발자 제이든

0개의 댓글