Lesson 5 of 8
Storybook - Component Documentation
Storybook is the industry standard for developing and documenting UI components in isolation. Every story is a living example with interactive controls - designers, developers, and QA can all explore component variants without running the app. It's the foundation of any professional design system.
Storybook Setup & CSF3 Stories
// 1. Install Storybook (Vite project)
npx storybook@latest init
// Writes to .storybook/main.ts, .storybook/preview.ts
// Creates src/stories/Introduction.mdx as a welcome doc
// 2. Story file - Button.stories.tsx
import type { Meta, StoryObj } from '@storybook/react';
import { Button } from './Button';
// Meta: component-level configuration
const meta = {
title: 'Design System/Button',
component: Button,
tags: ['autodocs'], // auto-generate Props table from TypeScript types
parameters: {
layout: 'centered', // 'centered' | 'fullscreen' | 'padded'
docs: {
description: { component: 'Primary action button. Use sparingly - one per screen.' },
},
},
argTypes: {
variant: {
control: { type: 'select' },
options: ['primary', 'secondary', 'danger', 'ghost'],
description: 'Visual style of the button',
},
size: {
control: { type: 'radio' },
options: ['sm', 'md', 'lg'],
},
disabled: { control: 'boolean' },
isLoading: { control: 'boolean' },
onClick: { action: 'clicked' }, // logs to Actions panel
},
} satisfies Meta<typeof Button>;
export default meta;
type Story = StoryObj<typeof meta>;
// Individual stories
export const Primary: Story = {
args: { variant: 'primary', children: 'Click me', size: 'md' },
};
export const Secondary: Story = {
args: { variant: 'secondary', children: 'Cancel', size: 'md' },
};
export const Danger: Story = {
args: { variant: 'danger', children: 'Delete', size: 'md' },
};
export const Loading: Story = {
args: { variant: 'primary', children: 'Saving...', isLoading: true },
};
// Story with play function - automated interaction tests
import { within, userEvent, expect } from '@storybook/test';
export const WithClickInteraction: Story = {
args: { variant: 'primary', children: 'Submit' },
play: async ({ canvasElement, args }) => {
const canvas = within(canvasElement);
const button = canvas.getByRole('button', { name: 'Submit' });
await userEvent.click(button);
expect(args.onClick).toHaveBeenCalled();
},
};
// Story with mocked API - for components with data fetching
import { http, HttpResponse } from 'msw';
export const WithData: Story = {
parameters: {
msw: {
handlers: [
http.get('/api/user', () => HttpResponse.json({ name: 'Alice', role: 'admin' })),
],
},
},
};Storybook - Design System Organization
// .storybook/main.ts - full configuration
import type { StorybookConfig } from '@storybook/react-vite';
const config: StorybookConfig = {
stories: ['../src/**/*.stories.@(js|jsx|mjs|ts|tsx)', '../src/**/*.mdx'],
addons: [
'@storybook/addon-links',
'@storybook/addon-essentials', // docs, controls, actions, viewport, backgrounds
'@storybook/addon-a11y', // accessibility audit panel
'@storybook/addon-interactions', // play function testing
'msw-storybook-addon', // mock API requests
],
framework: { name: '@storybook/react-vite', options: {} },
docs: { autodocs: 'tag' }, // auto-generate docs for stories with 'autodocs' tag
};
export default config;
// .storybook/preview.ts - global decorators and parameters
import type { Preview } from '@storybook/react';
import { initialize, mswLoader } from 'msw-storybook-addon';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { MemoryRouter } from 'react-router-dom';
import '../src/index.css';
initialize(); // initialize MSW for mocking
const preview: Preview = {
decorators: [
// Wrap every story with necessary providers
(Story) => (
<QueryClientProvider client={new QueryClient()}>
<MemoryRouter>
<Story />
</MemoryRouter>
</QueryClientProvider>
),
],
parameters: {
backgrounds: {
values: [
{ name: 'light', value: '#ffffff' },
{ name: 'dark', value: '#0f172a' },
{ name: 'gray', value: '#f8fafc' },
],
default: 'light',
},
viewport: {
defaultViewport: 'responsive',
},
},
loaders: [mswLoader], // enable MSW in stories
};
export default preview;
// Story organization by design system layer:
// Foundation: Color, Typography, Spacing, Icons
// Components: Button, Input, Modal, Toast, Tooltip
// Patterns: Form, DataTable, Navigation
// Pages: LoginPage, Dashboard, ProfilePageCommon Mistakes - Storybook
- Stories that require app context - without decorators wrapping Router or QueryClient, any story with hooks using those providers will crash. Set up global decorators in preview.ts
- Not using `autodocs` tag - you can write stories without auto-generated documentation, but adding `tags: ['autodocs']` to meta auto-generates a comprehensive Props table from TypeScript
- Hardcoding data in stories - use `args` for all data so controls can change it interactively; hardcoded strings in JSX can't be modified by the controls panel
- Storybook and MSW out of sync - if you mock APIs in both your app and Storybook differently, component behavior will differ; use the same handler definitions in both
- Forgetting to run visual regression tests - Storybook works with Chromatic for snapshot diffing; without it, visual regressions are caught only manually in code review
Tip
Tip
Practice Storybook Component Documentation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and flow for Storybook - Component Documentation
Practice Task
Note
Practice Task - (1) Write a working example of Storybook Component Documentation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Storybook Component Documentation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.
Key Takeaways
- Storybook is the industry standard for developing and documenting UI components in isolation.
- Stories that require app context - without decorators wrapping Router or QueryClient, any story with hooks using those providers will crash. Set up global decorators in preview.ts
- Not using `autodocs` tag - you can write stories without auto-generated documentation, but adding `tags: ['autodocs']` to meta auto-generates a comprehensive Props table from TypeScript
- Hardcoding data in stories - use `args` for all data so controls can change it interactively; hardcoded strings in JSX can't be modified by the controls panel
Finished this lesson?