Component Story Format 3 is hereAutomate with Chromatic
Storybook Day 2023
Back to Intro to Storybook
  • Get started
  • Simple component
  • Composite component
  • Data
  • Screens
  • Deploy
  • Addons
  • Conclusion
  • Contribute

Build a simple component

Build a simple component in isolation
This community translation has not been updated to the latest version of Storybook yet. Help us update it by applying the changes in the English guide to this translation. Pull requests are welcome.

We’ll build our UI following a Component-Driven Development (CDD) methodology. It’s a process that builds UIs from the “bottom up” starting with components and ending with screens. CDD helps you scale the amount of complexity you’re faced with as you build out the UI.


Task component in three states

Task is the core component in our app. Each task displays slightly differently depending on exactly what state it’s in. We display a checked (or unchecked) checkbox, some information about the task, and a “pin” button, allowing us to move tasks up and down the list. Putting this together, we’ll need these props:

  • title – a string describing the task
  • state - which list is the task currently in and is it checked off?

As we start to build Task, we first write our test states that correspond to the different types of tasks sketched above. Then we use Storybook to build the component in isolation using mocked data. We’ll “visual test” the component’s appearance given each state as we go.

This process is similar to Test-driven development (TDD) that we can call “Visual TDD”.

Get set up

First, let’s create the task component and its accompanying story file: components/Task.js and components/Task.stories.js.

We’ll begin with a basic implementation of the Task, simply taking in the attributes we know we’ll need and the two actions you can take on a task (to move it between lists):

import * as React from 'react';
import { TextInput, SafeAreaView } from 'react-native';
import { styles } from '../constants/globalStyles';

export default function Task({ task: { id, title, state }, onArchiveTask, onPinTask }) {
  return (
    <SafeAreaView style={styles.ListItem}>
      <TextInput value={title} editable={false} />

Above, we render straightforward markup for Task based on the existing HTML structure of the Todos app.

Below we build out Task’s three test states in the story file:

import * as React from 'react';
import { View } from 'react-native';
import { styles } from '../constants/globalStyles';
import { storiesOf } from '@storybook/react-native';
import { action } from '@storybook/addon-actions';
import Task from './Task';
export const task = {
  id: '1',
  title: 'Test Task',
  state: 'TASK_INBOX',
  updatedAt: new Date(2018, 0, 1, 9, 0),

export const actions = {
  onPinTask: action('onPinTask'),
  onArchiveTask: action('onArchiveTask'),
storiesOf('Task', module)
  .addDecorator((story) => <View style={styles.TaskBox}>{story()}</View>)
  .add('default', () => <Task task={task} {...actions} />)
  .add('pinned', () => <Task task={{ ...task, state: 'TASK_PINNED' }} {...actions} />)
  .add('archived', () => <Task task={{ ...task, state: 'TASK_ARCHIVED' }} {...actions} />);

There are two basic levels of organization in Storybook: the component and its child stories. Think of each story as a permutation of a component. You can have as many stories per component as you need.

  • Component
    • Story
    • Story
    • Story

To initiate Storybook we first call the storiesOf() function to register the component. We add a display name for the component –the name that appears on the sidebar in the Storybook app.

action() allows us to create a callback that appears in the actions panel of the Storybook UI when clicked. So when we build a pin button, we’ll be able to determine in the test UI if a button click is successful.

As we need to pass the same set of actions to all permutations of our component, it is convenient to bundle them up into a single actions variable and use React's {...actions} props expansion to pass them all at once. <Task {...actions}> is equivalent to <Task onPinTask={actions.onPinTask} onArchiveTask={actions.onArchiveTask}>.

Another nice thing about bundling the actions that a component needs is that you can export them and use them in stories for components that reuse this component, as we'll see later.

To define our stories, we call add() once for each of our test states to generate a story. The action story is a function that returns a rendered element (i.e. a component class with a set of props) in a given state---exactly like a Stateless Functional Component.

When creating a story we use a base task (task) to build out the shape of the task the component expects. This is typically modelled from what the true data looks like. Again, export-ing this shape will enable us to reuse it in later stories, as we'll see.

Actions help you verify interactions when building UI components in isolation. Oftentimes you won't have access to the functions and state you have in context of the app. Use action() to stub them in.


We also have to make one small change to the Storybook configuration setup (storybook/index.js) so it notices our recently created stories.

import { getStorybookUI, configure } from '@storybook/react-native';

import './rn-addons';

// import stories
configure(() => {
}, module);

const StorybookUIRoot = getStorybookUI({
  asyncStorage: null,

export default StorybookUIRoot;

Once we’ve done this, restarting the Storybook server should yield test cases for the three Task states in your simulator:

Build out the states

Now we have Storybook set up, styles imported, and test cases built out, we can quickly start the work of implementing the HTML of the component to match the design.

The component is still basic at the moment. First write the code that achieves the design without going into too much detail:

import * as React from 'react';
import { TextInput, SafeAreaView, View, TouchableOpacity } from 'react-native';
import { styles } from '../constants/globalStyles';
import PercolateIcons from '../constants/Percolate';

export default function Task({ task: { id, title, state }, onArchiveTask, onPinTask }) {
  return (
    <SafeAreaView style={styles.ListItem}>
      <TouchableOpacity onPress={() => onArchiveTask(id)}>
        {state !== 'TASK_ARCHIVED' ? (
          <View style={styles.CheckBox} />
        ) : (
          <PercolateIcons name="check" size={20} color={'#2cc5d2'} />
        placeholder="Input Title"
          state === 'TASK_ARCHIVED' ? styles.ListItemInputTaskArchived : styles.ListItemInputTask
      <TouchableOpacity onPress={() => onPinTask(id)}>
          color={state !== 'TASK_PINNED' ? '#eee' : '#26c6da'}

The additional markup from above combined with the styling we created earlier yields the following UI:

Specify data requirements

It’s best practice to use propTypes in React to specify the shape of data that a component expects. Not only is it self documenting, it also helps catch problems early.

import * as React from 'react';
import PropTypes from 'prop-types';

export default function Task({ task: { id, title, state }, onArchiveTask, onPinTask }) {
  // ...

Task.propTypes = {
  task: PropTypes.shape({
    id: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
    state: PropTypes.string.isRequired,
  onArchiveTask: PropTypes.func,
  onPinTask: PropTypes.func,

Now a warning in development will appear if the Task component is misused.

An alternative way to achieve the same purpose is to use a JavaScript type system like TypeScript to create a type for the component properties.

Component built!

We’ve now successfully built out a component without needing a server or running the entire frontend application. The next step is to build out the remaining Taskbox components one by one in a similar fashion.

As you can see, getting started building components in isolation is easy and fast. We can expect to produce a higher-quality UI with fewer bugs and more polish because it’s possible to dig in and test every possible state.

Automated Testing

Storybook gave us a great way to visually test our application during construction. The ‘stories’ will help ensure we don’t break our Task visually as we continue to develop the app. However, it is a completely manual process at this stage, and someone has to go to the effort of clicking through each test state and ensuring it renders well and without errors or warnings. Can’t we do that automatically?

Snapshot testing

Snapshot testing refers to the practice of recording the “known good” output of a component for a given input and then flagging the component whenever the output changes in future. This complements Storybook, because it’s a quick way to view the new version of a component and check out the changes.

Make sure your components render data that doesn't change, so that your snapshot tests won't fail each time. Watch out for things like dates or randomly generated values.

With the Storyshots addon a snapshot test is created for each of the stories. Use it by adding a development dependency on the package:

yarn add -D @storybook/addon-storyshots

Then create an components/__tests__/storybook.test.js file with the following:

import initStoryshots from '@storybook/addon-storyshots';

Once the above is done, we can run yarn test and see the following output:

Task test runner

We now have a snapshot test for each of our Task stories. If we change the implementation of Task, we’ll be prompted to verify the changes.

Should your snapshot tests fail at this stage, you must update the existing snapshots by running the test script with the flag -u. Or create a new script to address this issue.
Is this free guide helping you? Tweet to give kudos and help other devs find it.
Next Chapter
Composite component
Assemble a composite component out of simpler components
✍️ Edit on GitHub – PRs welcome!
Join the community
5,883 developers and counting
WhyWhy StorybookComponent-driven UI
Open source software

Maintained by
Special thanks to Netlify and CircleCI