Skip to content
This repository has been archived by the owner on Jun 29, 2020. It is now read-only.

How to use Storybook with React App

lucierabahi edited this page Jul 23, 2019 · 2 revisions

Storybook runs alongside your app in development mode:

  • first you create a React component, for example Todo.js
  • and then a corresponding Storybook file, for example Todo.stories.js.

It helps you build and test components in isolation.
With Storybook, we will follow a bottom-up approach, meaning that we will start with component and end with screen.

Setup Storybook

  1. Add storybook

npx -p @storybook/cli sb init

  1. Run storybook in development

yarn/npm storybook

For more details you can visit:

Storybook Quick Start Guide - Setup
Storybook for React - Setup

Develop application with Storybook

Todo app example

  1. Start with creating simple component with required properties, as required to build various states. For example, if you are building a 'Todo app', you need the two following properties for single todo component:
    • In progress tasks (default view)
    • Completed task (view when the task is completed, with a line through the title)
  2. Start to develop stories for the the component, using naming convention as Todo.stories.js.

For example:

//src//Todo.js

import React from 'react'

const Todo = ({todo: {id, todo, completed}}) => {
      const className = completed ? 'done' : null;
      return (
           <div className='todo'>
               <p className={className}>{todo}</p>
           </div>
      )
}

export default Todo;

Then story file as:

//src//Task.stories.js

import React from 'react'
import {storiesOf} from '@storybook/react'
import {action} from '@storybook/addon-actions'
import Todo from './Todo';

export const todo = {
id: 1, 
title: 'Buy more milk',
completed: false
}

export const actions = {
   onCompleteTodo: action('onCompletedTodo'),
   onRemoveTodo: action('onRemoveTodo')
}

//defined stories
storiesOf('Todo', module)
        .add('Default', () => <Task {...actions} todo={{...todo, completed: false}} />);
        .add('Completed', () => <Task {...actions} todo={{...todo, completed: true}} />);
}

For more information you can visit:

https://www.learnstorybook.com/react/en/simple-component/