Storybook for React

Kimberly Bone
The Startup
Published in
3 min readFeb 10, 2020
Storybook logo

Storybook is a tool that enables developers to create components interactively and independently in a separate environment. It is a collection of stories where each story is a function and a visual test case.

Storybook can be used with a variety of frameworks such as Angular, Vue, Ember, React etc. but in this article I’ll be working with React.

Luckily, there are only a couple steps to get started with Storybook.

First, cd into your project then type in npx -p @storybook/cli sb init into your command line. This will add Storybook to your project and the nice thing about is that it detects whether you are using Vue, React, Angular etc automatically. If it’s not successful in detecting your project type, you can select the project type from a given list in the terminal.

Second, run storybook with npm run storybook and you will see this pop up in your browser.

Welcome page in Storybook browser

In the Storybook document, they give a great example of what they call a “Basic Story” for a Button component.

Storybook will automatically update in the browser as you are coding. Looking at the button example, the Button.js file will look something like this.

import React from 'react';
import { action } from '@storybook/addon-actions';
import Button from './Button';
export default {
component: Button,
title: 'Button',
};
export const text = () => <Button onClick={action('Hellooo!')}>Hello Button</Button>;export const emoji = () => (
<Button onClick={action('Cha-ching!')}>
<span role="img" aria-label="so cool">
💎💎💎
</span>
</Button>
);

In your browser, it will look something like this:

Storybook Button component

Now if I click on it three times, the action that I typed (‘Cha-ching!’) will show under “Actions” every time I click on it:

Storybook actions after being clicked

I can also add styling globally or locally called “decorators” onto the components. You must import the decorator component first.

import { addDecorator } from '@storybook/react'

To add styling globally, you will need to create a function as a part of the default object.

export default {
title: 'Button',
component: Button,
decorators: [storyFn => <div style={{ backgroundColor: 'yellow' }}>{storyFn()}</div>]
};

To add styling locally, you will need to specify the story you want to apply the styling to.

Emoji.story = {
decorators: [storyFn => <div style={{ border: '5px solid red'}}>{storyFn()}</div>]
}

Your browser will then look something like this:

Storybook can help create more productive and smart applications. For all the front-end developers out there, it’s definitely worth looking into!

~Happy coding!~

Resources:

--

--

Kimberly Bone
The Startup

SWE with a passion for innovative technologies. I blog about technology, coffee & NYC. Let’s connect! https://www.linkedin.com/in/kimberly-bone-aa3952121/