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?

More than 1 year has passed since last update.

【StoryBook】コンポーネントを作成しカタログに登録してみる

Posted at

はじめに

StoryBookのインストールからコンポーネントをカタログに登録するところまで
学んだのでアウトプットのための本記事を作成してます。
本記事のゴールとしては自作のUIをカタログに登録し使用する事とする。

環境

next:14.0.4
tailwindcss:3.4.1
storybook": 7.6.9

SotryBookのインストール

次のコマンドでSotryBookのインストール。

npx storybook@latest init

インストールが終わると、プロジェクト直下に.storybookのディレクトリが作成される。

tailwindcssの適用

tailwindcssをドキュメントに沿ってインストール。

preview.tsに以下のインポートを追加。
これによりglobal.cssが読み込まれtailwindcssが有効になる。

import '../src/styles/globals.css'

コンポーネントの作成

今回は正方形のコンポーネントを作成する。
storiesフォルダの直下にSquare.tsxSquare.stories.tsフォルダを作成。
tailwindcssでしているする色の濃ゆさを3パターン準備し、
テンプレートリレテラルで背景色部分を設定してます。

Square.tsx
type Props ={
    ColorIntensity:200| 400 | 600;
};

export const Square = ({ColorIntensity}:Props) => {
    let bgColor = `bg-blue-${ColorIntensity}`;

    switch(ColorIntensity) {
        case 200:
            bgColor = 'bg-blue-200';
            break;
        case 400:
            bgColor = 'bg-blue-400';
            break;
        case 600:
            bgColor = 'bg-blue-600';
            break;
    }

  return (
    <div className={`${bgColor} w-20 h-20 p-2 rounded`} />
  )
}

メタデータの作成

コンポーネントのメタデータを定義していきます。
ストーリーのコンポーネント、タイトル、カタログ上の設定を行う。

Square.stories.ts
import { Meta, StoryObj } from "@storybook/react";
import { Square } from "./Square";

type Story = StoryObj<typeof meta>;

const meta:Meta<typeof Square> ={
  // ストーリーのコンポーネント
  component: Square,
  // ストーリーのタイトル
  title: 'Example/Square',
  argTypes:{
    ColorIntensity: {
      // カタログにおけるControlの表示形式
      control: { type: 'inline-radio'},
      options: [200, 400, 600]
    }
  },
  // ドキュメントの作成
  tags:['autodocs']
};

export default meta;

export const SampleSquare:Story = {};

ここまで出来たら以下のコマンドで起動してカタログを確認してみます。

npm run storybook

カタログにUIが表示されている事を確認できました。

storysample.gif

以下の記述により自動でコンポーネントのドキュメントを作成できます。

tags:['autodocs']

image.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?