Let's say we have a very simple button.
In the src/components/button.tsx
import { ComponentProps } from 'react';
type ButtonProps = ComponentProps<'button'>;
export const Button = (props: ButtonProps) => {
return <button {...props} />;
};
Next, we'll create the story for this component - called button.stories.tsx
Collocate this story file close to the button.tsx
component itself.
Let's get to the main point.
First, we need to import the Meta
and StoryObj
types to get some autocompletion in Typescript stories as well as the type safety.
Then, import the Button
component as well.
In the button.stories.tsx
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './button';
The Meta
contains metadata about the component's stories.
const meta: Meta<typeof Button> = {
title: 'Button',
component: Button,
};
export default meta;
The title
field controls where stories appear in the sidebar of the Storybook.
Afterward, let's define a type for the component story.
type Story = StoryObj<typeof Button>;
export const Primary: Story = {
render: () => <Button>Button</Button>
};
Each name export is a story for the Button
component.
Here we have Primary
is a first story.
You will need to export at least ONE name export if you want to see anything on the screen.
Here is the final story, it'll look something like this:
If you run Storybook using pnpm run storybook
you'll have something like the following:
It's not much. But we starting to see something, right?
Using the args
In our first story, instead of rendering the component itself, we can choose to use an args
object that will be used for the props
of the component being rendered in the story.
Let's take advantage of Storybook's Component Story Format.
export const Primary: Story = {
args: {
children: 'Primary Button',
},
};
You’ll notice that we can also adjust the props
in the Controls tab.
Here we have - Our Very Basic Button
Here is the end result of our button story at this point:
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './button';
const meta = {
title: "Button",
component: Button,
args: {
children: "My Button"
}
} satisfies Meta;
export default meta;
type Story = StoryObj<typeof Button>;
export const Primary: Story = {
children: 'Primary Button',
};
export const Secondary: Story = {
args: {
children: "Secondary"
}
}
Right now, our Button
component doesn’t do anything and it’s pretty ugly.
Let’s add some variants to the story. In the next article!
Cover Image source: Unsplash.com