본문 바로가기
seungchan.dev
뒤로

Storybook으로 React 버튼 컴포넌트의 story 만들기

Storybook의 기본 단위인 story 개념, 설치 명령, styled-components 버튼에 Small·Large story를 연결하는 예제를 정리했습니다.

1분 읽기#React

2023년에 쓴 글이라 지금과 다른 내용이 있을 수 있습니다.

Storybook이란

Storybook은 컴포넌트 단위의 UI 개발 도구입니다. React 프로젝트 안에 있는 많은 컴포넌트를 문서화할 수 있습니다. Storybook의 기본 단위는 story이며, 보통 UI 컴포넌트 하나는 하나 이상의 story를 가집니다.

설치

리액트 설치 text create-react-app@latest first-storybook --template=typescript

스토리북 설치 npx -p @storybook/cli sb init

버튼 컴포넌트 만들기

javascript
import styled from "styled-components";
 
interface NewButtonProps {
    label: string;
    size: "small" | "large";
    onClick?: () => void;
}
 
function NewButton({ label, size, onClick }: NewButtonProps) {
    return (
        <NewButtonStyle size={size}>
            <p>{label}</p>
        </NewButtonStyle>
    );
}
 
const NewButtonStyle = styled.div<{ size: "small" | "large" }>`
    background-color: red;
    color: whitesmoke;
    width: ${(props) => (props.size === "small" ? "75px" : "200px")};
    height: ${(props) => (props.size === "small" ? "75px" : "200px")};
    display: flex;
    align-items: center;
    justify-content: center;
`;
 
export default NewButton;
 

컴포넌트에 story 연결하기

javascript
import { ComponentMeta, ComponentStory } from "@storybook/react";
import NewButton from "./newButton";
 
export default {
    title: "Components/NewButton", // story 이름
    component: NewButton,
} as ComponentMeta<typeof NewButton>;
 
const Template: ComponentStory<typeof NewButton> = (args) => (
    <NewButton {...args} />
);
 
export const Small = Template.bind({});
Small.args = {
    size: "small",
    label: "small",
}; // Small의 props 지정
 
export const Large = Template.bind({});
Large.args = {
    size: "large",
    label: "large",
}; 
// Large의 props 지정!