0
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 2025-04-11

storybookのinstallと立ち上げ

npx storybook@latest init
yarn storybook

tailwind cssを使用する場合

./storybook/preview.tsに以下項目を追加

import type { Preview } from "@storybook/react";
+ import "@/app/globals.css";

const preview: Preview = {
  parameters: {
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/i,
      },
    },
  },
};

export default preview;

./componetsにstorybookファイルを配置する場合
(今回はcomponets/Buttonに配置)

./storybook/main.tsのstoriesに以下項目を追加

import type { StorybookConfig } from "@storybook/nextjs";

const config: StorybookConfig = {
  stories: [
    "../stories/**/*.mdx",
    "../stories/**/*.stories.@(js|jsx|mjs|ts|tsx)",
+   "../components/***/**/*.stories.@(js|jsx|ts|tsx)",
  ],
  addons: [
    "@storybook/addon-onboarding",
    "@storybook/addon-essentials",
    "@chromatic-com/storybook",
    "@storybook/addon-interactions",
  ],
  framework: {
    name: "@storybook/nextjs",
    options: {},
  },
  staticDirs: ["..\\public"],
};
export default config;

※他のディレクトリを参照したい場合は、その相対パスを指定する。

追記 25/04/13
以下のように記述することで、.stories.*の拡張子ファイルを読み込んでくれるようになる。

stories: ["../**/*.mdx", "../**/*.stories.@(js|jsx|mjs|ts|tsx)"],

実際にstorybookで作成したコンポーネントを表示してみる

interface IProps {
  bgColor?: string;
  onClick: () => void;
}

const Button = ({ bgColor, onClick }: IProps) => {
  return (
    <>
      <button
        onClick={onClick}
        className="border-2 rounded-md text-2xl p-2"
        style={{ backgroundColor: bgColor }}
      >
        test
      </button>
    </>
  );
};
export default Button;
import type { Meta, StoryObj } from "@storybook/react";
import { fn } from "@storybook/test";

import Button from "./button";

const meta = {
  title: "componets/Button",
  component: Button,
  parameters: {
    layout: "centered",
  },
  tags: ["autodocs"],
  // storybookのconotrolsから色変更ができる(1)
  argTypes: {
    bgColor: { control: "color" },
  },
  // args: { onClick: fn() },
} satisfies Meta<typeof Button>;

export default meta;
type Story = StoryObj<typeof meta>;

export const Defaullt: Story = {
  args: { onClick: fn() },
};

image.png


bgColorにコントローラーを設定しているため自由に色変更できるようになっている。(1)

image.png

storybookにはこれ以外にも様々な機能があるので、いろいろ試してみたい。

0
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
0
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?