DEV Community

Alex Spinov
Alex Spinov

Posted on

Storybook Has a Free API — Here's How to Build and Test UI Components in Isolation

Storybook is the industry standard for building and documenting UI components in isolation. It works with React, Vue, Angular, Svelte, and more — giving you a visual playground for your components.

Getting Started

npx storybook@latest init
npm run storybook
Enter fullscreen mode Exit fullscreen mode

Writing Stories

// Button.stories.ts
import type { Meta, StoryObj } from "@storybook/react";
import { Button } from "./Button";

const meta: Meta<typeof Button> = {
  title: "Components/Button",
  component: Button,
  argTypes: {
    variant: { control: "select", options: ["primary", "secondary", "danger"] },
    size: { control: "radio", options: ["sm", "md", "lg"] },
    disabled: { control: "boolean" }
  },
  tags: ["autodocs"]
};

export default meta;
type Story = StoryObj<typeof meta>;

export const Primary: Story = {
  args: { variant: "primary", children: "Click me", size: "md" }
};

export const Secondary: Story = {
  args: { variant: "secondary", children: "Cancel" }
};

export const Disabled: Story = {
  args: { variant: "primary", children: "Disabled", disabled: true }
};
Enter fullscreen mode Exit fullscreen mode

Interaction Testing

import { within, userEvent, expect } from "@storybook/test";

export const ClickTest: Story = {
  args: { children: "Submit" },
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    const button = canvas.getByRole("button");
    await userEvent.click(button);
    await expect(button).toHaveTextContent("Submit");
  }
};
Enter fullscreen mode Exit fullscreen mode

Decorators

export default {
  title: "Components/Card",
  component: Card,
  decorators: [
    (Story) => (
      <div style={{ padding: "2rem", background: "#f5f5f5" }}>
        <Story />
      </div>
    )
  ]
};
Enter fullscreen mode Exit fullscreen mode

Addons

// .storybook/main.ts
export default {
  stories: ["../src/**/*.stories.@(ts|tsx)"],
  addons: [
    "@storybook/addon-essentials",  // Controls, Actions, Viewport, Docs
    "@storybook/addon-a11y",         // Accessibility checks
    "@storybook/addon-interactions"  // Interaction testing
  ],
  framework: "@storybook/react-vite"
};
Enter fullscreen mode Exit fullscreen mode

Visual Testing with Chromatic

npx chromatic --project-token=YOUR_TOKEN
Enter fullscreen mode Exit fullscreen mode

Chromatic captures screenshots of every story and detects visual changes in PRs.


Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.

Top comments (0)