Skip to content

Instantly share code, notes, and snippets.

@lightsound
Created January 12, 2022 11:40
Show Gist options
  • Save lightsound/fdd7ec6719923ca1db123ca68c76d333 to your computer and use it in GitHub Desktop.
Save lightsound/fdd7ec6719923ca1db123ca68c76d333 to your computer and use it in GitHub Desktop.
Storybookのテンプレートを削減するためのファクトリー関数
import { AnyFramework, ComponentTitle, StoryAnnotations } from '@storybook/csf'
import { ComponentMeta, ComponentStory } from '@storybook/react'
import { VFC } from 'react'
export const createStorybookFactory = <P extends object>(Component: VFC<P>) => {
const Template = ((args) => <Component {...args} />) as ComponentStory<
typeof Component
>
const Default = Template.bind({})
Default.storyName = Component.displayName
return {
Default,
createStory: (options?: StoryAnnotations<AnyFramework, P>) => {
const story = Template.bind({})
return options ? { ...story, ...options } : story
},
createMeta: (
title: ComponentTitle,
options?: Omit<ComponentMeta<typeof Component>, 'title' | 'component'>
) => {
return {
...options,
parameters: {
controls: { hideNoControlsWarning: true },
...options?.parameters,
},
title: `${title}/${Component.displayName}`,
component: Component,
}
},
}
}
@lightsound
Copy link
Author

例えばこんな感じで使えます

import { createStorybookFactory } from '@/src/utils/createStorybookFactory'
import { LinkButton } from './index'

const { createMeta, createStory, Default } = createStorybookFactory(LinkButton)

export default createMeta('Components/Button', {
  args: { img: '', children: 'Some Text' },
})

const ImageButton = createStory({
  args: { img: 'https://source.unsplash.com/random' },
})

export { Default, ImageButton }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment