1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Storybook入門

Last updated at Posted at 2024-03-07

はじめに

Storybookは、Reactやその他のフロントエンドフレームワークで使用されるUIコンポーネントを開発、テスト、文書化するためのツールです。
主な目的は、個々のUIコンポーネントを分離して、それらがどのように見えるか、どのように動作するかを視覚的に確認し、テストすることです。
そうすることで、デザイナーとの連携が取りやすくなったり、アプリケーションを起動しなくてもUIコンポーネントの動作確認ができるようになります。

インストール

今回は、ReactとTypeScriptを使用するので、Reactのプロジェクトを立ち上げます。

npx create-react-app study-storybook --template typescript

プロジェクトが立ち上がったら、以下のコマンドでStorybookをインストールします。

npx storybook init

以下のようなファイルが作成されます。
初期では、Button, Header, Pageの3つのストーリーが作成されています。
スクリーンショット 2024-03-07 22.47.20.png

Storybookを起動

Storybookがインストールできたら、Storybookを立ち上げてみます。

 npm run storybook

すると、以下のような画面が表示されます。
スクリーンショット 2024-03-07 22.49.07.png

初期では「Button」「Header」「Page」の3つのストーリーが自動で作成されています。
今回は、Buttonコンポーネントをインポートして、ストーリーを作っていくので、自動で作成された「Storybook」フォルダは削除します。
スクリーンショット 2024-03-07 22.51.19.png

ストーリーを作成しよう

ボタンストーリーを作成するために、まずボタンコンポーネントを作成します。このコンポーネントは、次のようになります。

components/Button.tsx
import { FC } from "react";

interface ButtonProps {
  label: string;
  primary?: boolean;
  onClick: () => void;
}

const Button: React.FC<ButtonProps> = ({ label, primary, onClick }) => {
  const buttonStyle = primary
    ? { backgroundColor: "red", color: "white" }
    : { backgroundColor: "white", color: "red" };
  return (
    <button style={buttonStyle} onClick={onClick}>
      {label}
    </button>
  );
};

export default Button;

このコンポーネントは、label(ボタンのテキスト)、primary(プライマリボタンかどうかを示すブール値)、onClick(クリック時のイベントハンドラー)の3つのプロパティを受け取ります。primary プロパティは省略可能で、省略された場合はデフォルトで false が設定されます。ボタンのスタイルはprimary プロパティの値に応じて変更されます。

次に、ストーリーを作成します。ボタンコンポーネントに関するストーリーをまとめるためのモジュールを components/Button.stories.tsx ファイルに作成します。以下のようになります

components/Button.stories.tsx
import Button from "./Button";
import type { Meta, StoryObj } from "@storybook/react";

// ストーリーのメタ情報を定義します。
const meta = {
  title: "Button", // ストーリーのタイトル
  component: Button, // ストーリーで使用するコンポーネント
} as Meta<typeof Button>;

export default meta;

type Story = StoryObj<typeof Button>;

// Primary ボタンのストーリーを定義します。
export const Primary: Story = {
  args: {
    label: "Primaryボタン",
    primary: true,
  },
};

// Normal ボタンのストーリーを定義します。
export const Normal: Story = {
  args: {
    label: "Normalボタン",
    primary: false,
  },
};

それでは、作成したストーリーを見てみましょう。
npm run storybookコマンドを実行し、Storybookを起動します。
すると、以下のように作成した2つのストーリーが表示されます。

スクリーンショット 2024-03-07 22.58.37.png

スクリーンショット 2024-03-07 22.57.55.png

最後に

他にも色々な記事を書いているので、よければ読んでいってください、、、

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?