Skip to content

Storybook

thomran edited this page Mar 8, 2021 · 8 revisions

Storybook

The following section will describe how Storybook can and should be used.

Starting Storybooks

To start Storybooks Launch your local instance of Storybook with:

yarn storybook

Then you can view your Storybook at http://localhost:6006

Creating Storybooks

All storybooks should be saved in src/stories/. The file should be named "Component name".stories.tsx. Import the component and the component's props, Meta and Story.

import { Meta } from '@storybook/react/types-6-0';
import { Story } from '@storybook/react';
import ComponentName, { ComponentProps } from '../components/ComponentName';

The default export metadata controls how Storybook lists your stories and provides information used by addons. For example, here’s the default export for a story file Component.stories.tsx:

export default {
    title: 'Component/ComponentName',
    component: ComponentName,
} as Meta;

There are multiple ways to create a story, so you may want to read the documentation.

A story is a function that describes how to render a component. One can have multiple stories per component. The simplest way to create stories is to render a component with different arguments multiple times.

export const Primary: React.VFC<ComponentProps> = () => <Component background="#ff0" label="Button" />;
export const Secondary: React.VFC<ComponentProps> = () => <Component background="#ff0" label="πŸ˜„πŸ‘πŸ˜πŸ’―" />;
export const Tertiary: React.VFC<ComponentProps> = () => <Component background="#ff0" label="πŸ“šπŸ“•πŸ“ˆπŸ€“" />

You can also refine this pattern by defining a master template for a component’s stories that allows you to pass in args. This reduces the unique code you’ll need to write and maintain for each story.

// We create a β€œtemplate” of how args map to rendering
const Template: Story<ComponentProps> = (args) => <Component {...args} />;

// Each story then reuses that template
export const Primary = Template.bind({});
Primary.args = { background: 'red', label: 'Button' };

export const Secondary = Template.bind({});
Secondary.args = { background: 'green', label: 'πŸ˜„πŸ‘πŸ˜πŸ’―' };

export const Tertiary = Template.bind({});
Tertiary.args = { ...Primary.args, label: 'πŸ“šπŸ“•πŸ“ˆπŸ€“' };

You will be able to view the components in your Storybook at http://localhost:6006 now.

Read more here: How to write stories.