Storybook tutorial: build and test UI components in isolation
By Flavio
Updated
Tagged: React
Use Storybook with React to develop components in isolation, model loading and error states, test interactions and accessibility, and run CI.
Most components don’t have just one look. Think of a user card: it might be loading, filled in with normal data, missing an avatar, wrapping a long name, or sitting in an error state. Clicking through a full app just to trigger each of those states gets tedious fast.
Storybook lets you render components in isolation, outside your app. Each story captures one state by passing normal props to the component. In this tutorial, we’ll add Storybook to a React project, build a small UserCard component alongside its stories, and finish by setting up interaction and accessibility tests that run in CI.
Install Storybook
We’ll use Storybook 10 here, which requires Node.js 20+, npm 10+, and Vite 5+. Inside an existing React project powered by Vite, run the initializer:
npm create storybook@10
That command detects your framework, installs the packages you need, creates a .storybook folder, and drops in a few example stories so you can see how things are wired up. Once it finishes, start the Storybook dev server:
npm run storybook
Storybook opens in its own browser tab, completely separate from your app. You’ll see your stories listed in the sidebar and the selected component rendered on the canvas.
Build the component
Let’s set up a folder for our component with this file layout:
src/
assets/
ada-lovelace.jpg
components/
UserCard/
UserCard.css
UserCard.jsx
UserCard.stories.jsx
Drop any small local image in as ada-lovelace.jpg. Keeping assets local means your stories still work offline without relying on external URLs.
Next, create src/components/UserCard/UserCard.jsx:
import './UserCard.css'
export function UserCard({
name,
role,
avatarUrl,
headingTag = 'h2',
loading = false,
error = '',
onMessage,
}) {
const Heading = headingTag
if (loading) {
return (
<article aria-busy="true" className="user-card">
<p>Loading user...</p>
</article>
)
}
if (error) {
return (
<article className="user-card" role="alert">
<p>{error}</p>
</article>
)
}
return (
<article className="user-card">
{avatarUrl ? (
<img src={avatarUrl} alt="" width="64" height="64" />
) : (
<span aria-hidden="true" className="user-card__placeholder">
{name.slice(0, 1)}
</span>
)}
<div>
<Heading className="user-card__name">{name}</Heading>
<p>{role}</p>
<button type="button" onClick={() => onMessage(name)}>
Message {name}
</button>
</div>
</article>
)
}
Notice that the component takes the heading tag as a prop. A reusable card has no way of knowing whether it’ll sit under an h2, an h3, or something else on the page where it’s rendered, so letting the caller choose keeps the heading hierarchy clean.
Now add the styles in src/components/UserCard/UserCard.css:
.user-card {
display: flex;
gap: 16px;
align-items: flex-start;
padding: 16px;
color: #171717;
background: #fff;
border: 1px solid #d4d4d4;
}
.user-card img,
.user-card__placeholder {
flex: 0 0 64px;
width: 64px;
height: 64px;
}
.user-card__placeholder {
display: grid;
place-items: center;
background: #e5e5e5;
}
.user-card__name {
margin: 0;
overflow-wrap: anywhere;
}
.user-card p {
overflow-wrap: anywhere;
}
[data-theme='dark'] .user-card {
color: #fafafa;
background: #171717;
border-color: #525252;
}
[data-theme='dark'] .user-card__placeholder {
background: #404040;
}
Always import your real production component into your stories instead of maintaining a separate Storybook-only version. That way, any change you make to the card shows up in both places immediately.
Write the first story
Create src/components/UserCard/UserCard.stories.jsx right next to the component:
import { fn } from 'storybook/test'
import adaAvatar from '../../assets/ada-lovelace.jpg'
import { UserCard } from './UserCard'
const meta = {
title: 'People/UserCard',
component: UserCard,
tags: ['autodocs'],
argTypes: {
headingTag: {
control: 'select',
options: ['h1', 'h2', 'h3', 'h4'],
},
role: {
control: 'text',
description: 'The role shown below the name',
},
avatarUrl: {
control: 'text',
},
},
args: {
name: 'Ada Lovelace',
role: 'Mathematician',
avatarUrl: '',
headingTag: 'h1',
loading: false,
error: '',
onMessage: fn(),
},
}
export default meta
export const Default = {
args: {
avatarUrl: adaAvatar,
},
}
The default export holds metadata for the component, and each named export defines a story. The args object sets the props Storybook passes to UserCard, while fn() creates a spy that records button clicks in the UI and lets tests assert on them later.
Putting a full set of valid default props in meta saves a lot of repetition. Every story starts from a working card and only overrides the specific props it cares about. Since the card is the only thing on the page in this isolated view, the story uses an h1, and when you drop the card into your real app you’ll pass whatever headingTag fits the surrounding page.
Model every important state
Now let’s add stories for the other states we care about:
export const WithoutAvatar = {
args: {
name: 'Grace Hopper',
role: 'Computer scientist',
avatarUrl: '',
},
}
export const Loading = {
args: {
loading: true,
},
}
export const Error = {
args: {
error: 'Could not load this user',
},
}
export const LongContent = {
args: {
name: 'A very long name that must not break the card layout',
role: 'Principal engineer working across several product teams',
avatarUrl: '',
},
}
Having these in the sidebar makes edge cases effortless to inspect while you’re working. You don’t have to force an API failure just to check the error layout, or tweak database records to test how a very long name wraps. You just click the story, see the exact state, and tweak your CSS or markup until it looks right.
Use controls
Storybook builds interactive controls automatically from your args. Open the Controls panel and try changing name, role, or loading live. In our meta object, argTypes configures the heading selector and adds a description for role, while Storybook infers the rest directly from the component and its args.
Try flipping loading off while viewing the Loading story. Because meta defines a complete set of default args, the card falls back to valid data cleanly instead of breaking. Controls are great for poking around and testing ideas, while named stories lock in the specific states you’ve reviewed so you can revisit them and run them as automated tests.
Add a decorator
Most real components need some surrounding layout or React context to look and behave properly. You can provide that by adding a decorator to wrap your stories:
decorators: [
(Story) => (
<div style={{ maxWidth: 420, padding: 24 }}>
<Story />
</div>
),
],
Drop that decorators property into the existing meta object, and Storybook will wrap every UserCard story with it. If you need a wrapper across all components, put it in .storybook/preview.jsx instead:
import '../src/index.css'
export default {
decorators: [
(Story) => (
<div className="storybook-page">
<Story />
</div>
),
],
}
Include the providers and global CSS your components genuinely depend on, and skip the rest of the app shell. Keeping the wrapper lean makes stories faster to read and debug.
Write an interaction test
Any story that renders already gives you a basic smoke test, since it proves the component mounts without throwing. To test user interactions, attach a play function to a story.
Start by updating the import at the top of UserCard.stories.jsx:
import { expect, fn } from 'storybook/test'
Then add a story with a play function that clicks the button and verifies the callback:
export const SendsMessage = {
args: {
name: 'Ada Lovelace',
role: 'Mathematician',
avatarUrl: '',
},
play: async ({ args, canvas, userEvent }) => {
const button = canvas.getByRole('button', {
name: 'Message Ada Lovelace',
})
await userEvent.click(button)
await expect(args.onMessage).toHaveBeenCalledWith(
'Ada Lovelace'
)
},
}
Storybook runs the play function right after the story renders. Inside it, canvas gives you Testing Library queries scoped to that story. Querying by role and accessible name matches how someone using assistive technology locates the control, and you can step through every action in the Interactions panel whenever a test fails.
Test keyboard behavior
Because we used a native <button> element, keyboard activation works out of the box. You can lock in that behavior with another story:
export const KeyboardMessage = {
args: {
name: 'Grace Hopper',
role: 'Computer scientist',
avatarUrl: '',
},
play: async ({ args, canvas, userEvent }) => {
await userEvent.tab()
const button = canvas.getByRole('button', {
name: 'Message Grace Hopper',
})
await expect(button).toHaveFocus()
await userEvent.keyboard('{Enter}')
await expect(args.onMessage).toHaveBeenCalled()
},
}
If your story’s decorator or wrapper includes other focusable elements before the button, tab through them in the real order instead of calling focus manually. Forcing focus in a test can easily mask a broken tab order.
Add accessibility checks
If the initializer didn’t install the accessibility addon for you, add it now:
npx storybook add @storybook/addon-a11y
Once it’s installed, the Accessibility panel runs automated rules against every rendered story. To turn those violations into test failures, add the a11y parameter to your existing meta object:
parameters: {
a11y: {
test: 'error',
},
},
The error setting tells the Vitest addon to run accessibility checks and fail the test suite whenever it spots a violation. That catches things like:
- insufficient color contrast
- missing form labels
- invalid ARIA attributes
- some heading and landmark issues
Pair those automated checks with quick manual passes using your keyboard and a screen reader to catch focus and announcement issues that static rules miss. You’ll also notice our decorative avatar uses alt="" because the person’s name is already rendered as visible text right next to it, so repeating the name in the alt attribute would only create extra noise.
View mobile and dark states
You can use Storybook’s viewport tools to check how a component behaves on phone-sized screens, and you can pin a narrow viewport directly in a story using globals:
export const Mobile = {
args: {
name: 'Ada Lovelace',
role: 'Mathematician',
avatarUrl: '',
},
globals: {
viewport: {
value: 'mobile1',
isRotated: false,
},
},
}
For themes, write a decorator that applies the same class or data attribute your app uses. Since our stylesheet looks for data-theme="dark", we can add a dark mode story that wraps the exact same UserCard component:
export const Dark = {
decorators: [
(Story) => (
<div data-theme="dark" style={{ padding: 24 }}>
<Story />
</div>
),
],
}
Always theme your existing component rather than building a separate dark variant.
Mock data at the network boundary
When a component fetches its own data, you don’t want its stories depending on a running development API. Instead, use Storybook’s network mocking setup (usually Mock Service Worker) to define handlers for the responses you care about:
- success
- empty response
- slow response
- server error
Your component keeps calling fetch() just like it does in production, while the story controls what comes back over the wire. That tests the real code path instead of forcing you to add something like a fakeError prop that only exists for Storybook.
Run stories as tests
In a Vite-based Storybook setup, you can turn your stories into real browser tests by adding the Vitest addon:
npx storybook add @storybook/addon-vitest
Storybook Test runs render checks, play functions, and your configured accessibility rules both inside the Storybook UI and from the command line. Once the addon generates its test scripts, you can wire them into a GitHub Actions workflow like this:
jobs:
test-storybook:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
- run: npx playwright install --with-deps chromium
- run: npm run test-storybook
Under the hood, Storybook’s test runner uses Vitest browser mode and Playwright to render each story, which is why the workflow installs Chromium first. Because we set a11y.test to error, that command runs render tests, play functions, and accessibility checks together.
It’s also worth running a static Storybook build in CI:
npm run build-storybook
A full build catches missing assets, broken imports, and config quirks that only slip by in the dev server.
What deserves a story?
Skip writing stories for random prop combinations just for coverage. Focus on the states that matter in your app:
- normal states
- loading, empty, and error states
- important variants
- boundary content
- responsive layouts
- permission or role differences
- interaction flows
- bugs that should never return
Whenever someone reports a UI bug, reproduce it as a story before you touch the component code. Once you fix it, leave that story in place as a permanent regression test.
Keep stories close to the component
Keep each story file right beside the component it belongs to:
src/
assets/
ada-lovelace.jpg
components/
UserCard/
UserCard.css
UserCard.jsx
UserCard.stories.jsx
Treating stories as part of the component itself makes it much easier to keep them current. Whenever you change a component’s props or behavior, update its stories in the same commit so they keep reflecting real app states instead of drifting out of date while still technically rendering.
Want me to talk about your product? You can sponsor this site.