Intro to Storybook for React — Optimize and Quickly Scale Your React Components with Confidence

Sunny Singh
11 min readAug 12, 2020

Quick Links

  1. What is Storybook?
    How Does Storybook Work?
    Why Should I Care about Storybook?
    What is a “Story”?
  2. Installation
    Automatic Installation (NPX)
    Manual Installation (Yarn)
  3. Basics of Storybook
    Section 0: Import
    Section 1: Initial Data
    Section 2: Prop Functions
    Section 3: Helper Functions
    Section 4: Variations
  4. Installing Official Addons
  5. Conclusion

The tool we use for editing UI is React Storybook. It is the perfect place to make sure your work aligns with designs to the pixel across breakpoints. You get fast hot module reloading and a couple checkboxes to enable/disable browser features like Flexbox.

Adam Neary (Engineer at Airbnb)

Do you ever just look at your components folder and see a giant mess of unorganized components? Do you get the feeling that you’ve already built the component you’re working on but just don’t know where it is? Are you having to spend more time understanding how components that others have made than actually using those components?

That’s where Storybook can help you solve all of these problems. No longer will you have a giant mess of components. No longer will you have to go on treasure hunts to find where existing components are and what they look like. No longer will you have to spend huge amounts of time to understand existing components.

Storybook has the potential to speed your software development cycle and make front-end development a pleasurable experience.

Storybook is a UI component tool that can be used as the single source of truth for all your components. Storybook helps you to develop, organize, document and test your components.

Development is made easier by allowing you to specify edge cases in your “stories.” More about stories later. Organization is made easier with the builtin configurations that can be made to stories. Documentation is made easier with the ability to use MDX, which is essentially a combination of Markdown and JSX. Testing is made easier with Storybook’s integration into popular testing frameworks such as Jest.

Storybook uses Webpack to watch your Javascript files and launch the Storybook local server. If you’re not familiar with Webpack, I recommend you to read this article where I go into what Webpack is.

Whenever you make an update to your components, if you’ve configured your Webpack correctly, Storybook will pick up on those changes and automatically update the component without you having to reload the page. This is called “hot reloading” and it can be extremely helpful if your React code lives within a backend environment such as Laravel or Django where you have to reload the page to see changes.

Need to build something? Perhaps you can check Storybook to see if you already have something similar built or if the sub-components exist. Storybook has the full potential to be your development team’s go-to source for anything related to React components.

Some other positive side effects of using Storybook in your development environment include:

  • Component Reusability: Using the built-in search bar in Storybook, you can find existing components easier and start to quickly build on top of them to make more complex components.
  • Collaboration with Designers: Storybook comes with options to integrate with various UX tools to enable collaboration between front-end developers and designers.
  • Official Addons: Storybook offers many official addons that you can use to make your Storybook better. Furthermore, Storybook offers an API in case you want to create a custom addon.
  • Easier Onboarding: Whenever a new developer is added to a team, they can quickly learn which components exist and how to use them. Spend less time and money on training.
  • Faster Prototyping: Using the official addon “Links”, you can start to stitch different components together right within Storybook to create quick prototypes of user experiences.

A story captures the rendered state of a UI component. Developers write multiple stories per component that describe all the “interesting” states a component can support.

Official Storybook documentation

A story is essentially an “instance” of your component and how it would look when it is rendered.

For example, if you’ve created a button, you can create a story file that shows all the different variations (rounded, soft border radius, light shadow, etc.) of that button. Each of those variations is considered a “story.”

The general rule of thumb is that each component will have a corresponding story file that allows you to write out all the different variations that component can have.

Now that you have a better idea of what Storyboard is, let’s get into the actual integration of Storybook into your project as you won’t really experience how powerful it can be until you use it yourself in your own project.

Let’s take Storybook on that “test drive”.

There are two methods for installing Storybook. The first method is using NPX for a quick and automatic installation. The second method is using Yarn to manually install and configure Storybook.

Using NPX — Automatic Installation
Navigate to the root directory of your React project and run the following command:

$ npx -p @storybook/cli sb init

During the installation process, Storybook will analyze your project’s dependencies and provide you with a default configuration based on that. The installation process will also give you some boilerplate stories to learn from.

After this, you can run the following command to start running Storybook:

$ npm run storybook

Using Yarn — Manual Installation
Navigate to the root directory of your React project and run the following command:

$ yarn add @storybook/react -D

This command will install the Storybook React library as a developer dependency. From here, you want to create a folder at the root level called .storybook and inside of that folder, create a file named main.js , which is going to look like the following:

// .storybook/main.jsmodule.exports = {
stories: ['../src/**/*.stories.js)']
};

This will configure Storybook’s Webpack to look for stories in the src folder. It will look for any files that have the .stories.js extension.

If you have a custom Webpack configuration that you would like to use, you can tell main.js to use your custom Webpack configuration. You would do this by importing your webpack.config.js file. Below is an example:

// .storybook/main.jsconst customConfig = require('../webpack.config.js');module.exports = {
stories: ['../src/**/*.stories.js'],
webpackFinal: (config) => {
return {
...config,
module: {
...config.module,
rules: customConfig.module.rules
}
};
}
};

From here, you can run Storybook by running the following command:

$ yarn start-storybook

Optional: In your package.json file, you can define a “script” that can be used a shortcut to run yarn start-storybook . You would this by adding the following to your package.json file:

{
"name": "Hello World",
"version": "1.0.0",
... "scripts": {
"your-custom-command": "start-storybook"
},
...}

From here, in order to run storybook, you would do the following:

$ yarn run your-custom-command

If you’ve successfully installed Storybook, move to the next step. If you are having trouble, check out the official documentation and/or contact me directly on Twitter.

Once you’ve launched Storybook, it should automatically launch your web browser and go to the appropriate port and URL.

After the installation, you may have noticed a stories folder in your project that already has some boilerplate story files. You can delete these files if you don’t care about keeping default boilerplate components.

After using Storybook for some time, I have developed a structure for a story file that has helped me streamline the process to create a story file. It has saved me and other developers a lot of time. This isn’t something you’ll find anywhere else on the internet, so if you get some value out of it, be sure to leave some claps so others can find this structure too.

Below is what the structure of the file looks like, and yes, I love creating ASCII art to organize my code:

// System Libraries
import React from 'react';
// Components
import ComponentName from '../components/ComponentName';
// Storybook Config
export default {
component: ComponentName,
title: 'SectionName | GroupName/ComponentName'
};
/* ------------------------ *\
| Storybook File |
|----------------------------|
| 1. Initial Data |
| 2. Prop Functions |
| 3. Helper Functions |
| 4. Variations |
\* ------------------------ */
/* ------------------- *\
| 1. Initial Data |
\* ------------------- */
const initialData = [...];/* ------------------- *\
| 2. Prop Functions |
\* ------------------- */
const someFunction = () => {
someHelperFunction();
...
};
/* ------------------- *\
| 3. Helper Functions |
\* ------------------- */
const someHelperFunction = () => {...};/* ------------------- *\
| 4. Variations |
\* ------------------- */
export const defaultView = () => {
return (
<ComponentName data={initialData} onRun={someFunction} />
);
};

Let’s take a look into the different parts of a story file and what they do.

Section 0a: Importing your Components and React
At the top of your story file, make sure to import the component(s) that will be used for this story as well as React.

Section 0b: Storybook Metadata
After importing your component(s), you want to define the metadata of that story file. In order to set the metadata:

export default {
title: 'ComponentName',
component: ComponentName
}

You can define which “group” or “section” that a component belongs by modifying the title.

In order to “group” the story, the title would look like GroupName/ComponentName and you will see your story grouped into a folder named “GroupName”. This can be helpful to separate components into categories. For example, you can have a group called “Typography” which includes all your text-based components.

In order to put a story under a “section”, the title would look like SectionName | ComponentName and you will now see a small header named “SectionName” that will help to spatially separate your stories from the others. This can be helpful if there are components specific to a workflow.

Finally, you can combine both the pipe operator (|) and the forward slash operator (/) to put a story in both a section and group. The section name would simply come first, followed by the pipe, then the group name and finally the story’s name. Going off the same example, your title would look like: SectionName | GroupName/ComponentName and you will see your story both sectioned off and under a group folder.

Section 1: Initial Data
If your component requires some data to be passed to it for it to work, you can define some initial data that can be passed in through props.

For example, currently at work, I’ve been working on a drag-and-drop editor to group individuals together. My component requires an initial array of objects that define the individuals to work. It’s in this Initial Data section where I defined a dummy array of objects and passed it into my component.

If you really need access to Redux, there are 3rd party libraries out there that allow Storybook to access Redux.

Section 2: Prop Functions
This is where you would define any functions that need to be passed into the components. For example, what should a button do when it is pressed? In this section is where you would define that function and pass it to the component.

Section 3: Helper Functions
If several of your prop functions require some shared logic, you can create a helper function that can help to shorten your file. These functions are not meant to be passed into the component. They’re meant to “help” the prop functions.

Step 4: Variations
This is where you would create all of the various variations that your component can take on. Perhaps your button takes in a prop that tells if the button should be full width or not. These are two different variations of the same button. This example would look like the following:

/* ------------------- *\
| 4. Variations |
\* ------------------- */
export const fullWidthButton = () => {
return (
<Button innerText="Press Me" fullWidth={true} />
);
};
export const nonFullWidthButton = () => {
return (
<Button innerText="Press Me" fullWidth={false} />
);
};

Now you will see both of those variations as stories in Storybook. You can now edit both the full width button and the non-full width button at the same time and see the visual changes.

Storybook by itself is extremely powerful, however, you can install Addons that can take Storybook to a whole new level. Installing a new official addon is a rather simple process. Let’s walk through how you would install the Links addon.

  1. If you are running Storybook, kill the process.
  2. Run yarn add @storybook/addon-links -D to install the package.
  3. Go to .storybook/main.js and modify the code to look like the following:
module.exports = {
stories: ['...'],
addons: ['@storybook/addon-links'],
...
};

3. Restart Storybook and you will be able to start the Links addon.

Each addon has its own way of doing things so it’s helpful to look into their respective documentations. For example, if you install the Docs addon, you will be exposed to MDX, which is a mix of Markdown and JSX. If you install the Knobs addon, you will have to work with in its own way.

Storybook is a UI tool that can absolutely transform the efficiency of any developer or team of developers. Use it as your single source of truth for all your components and you will experience the benefits, which include:

  1. Component reusability/scability
  2. Collaboration with designers
  3. Easier onboarding of new developers
  4. Faster prototyping of user experiences
  5. Get more upgrades through addons

If you’re deciding to pull the trigger and learn Storybook, it would also be helpful to look into Styled Components for styling. If you’re curious about Styled Components, check out the article below:

Hopefully that helps you get started with Storybook. However, if you are having any trouble with Storybook, feel free to reach out to me via email or Twitter. Thanks for reading!

--

--

Sunny Singh

Backend developer passionate about leveraging practical solutions. Sharing insights on using software development and AI to solve problems. Connect for more!