Storybookでchildrenを持つComponentのstoriesを書く

AtomicDesignでTableを定義してみようと思い試した過程でのメモ
調べても本家しかまとまってなかったのでメモ。

下記のようなTableコンポーネントを定義

import { PropsWithChildren } from "react";
import './Table.scss'

interface TableProps {
    [key: string]: any
}

export const Table = (props:  PropsWithChildren<TableProps>) => {
    return (
        <table {...props}>
            {props.children}
        </table>
    );
}

それでstorybookでは、この中身を好きにいじりながら確認したい。
結論:renderを使う。

import type { Meta, StoryObj } from '@storybook/react';
import { Table } from './Table';

const meta = {
    title: 'tamago/Atoms/Table',
    component: Table,
    parameters: {
        layout: 'centered',
    },
    tags: ['autodocs'],
    render: ({ ...args }) => (
        <Table {...args}>
            <thead>
                <tr>
                    <th>Header 1</th>
                    <th>Header 2</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>Cell 1</td>
                    <td>Cell 2</td>
                </tr>
            </tbody>
        </Table>
    )

} satisfies Meta<typeof Table>;

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

export const Primary: Story = {
  args: {
    label: 'Button',
  },
};

export const Secondary: Story = {
  args: {
    label: 'Button',
    render: ({ ...args }) => (
    <Table {...args}>
        <thead>
            <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            </tr>
        </thead>
        <tbody>
            <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
            </tr>
            <tr>
            <td>Cell 3</td>
            <td>Cell 5</td>
            </tr>
        </tbody>
    </Table>
  )
  },
};

Meta内部に宣言することで全てのStoryに適用され、
Storyで再定義することで、上書きして表示されます。

PrimaryとSecondaryでテーブルの中身が変わってることを確認

参考
Storybook Args
Storybook Stories for multiple component

今回使わなかったけどArgsドキュメントにある この辺りとか便利そう。

上部へスクロール