React Storybook

Introduction to Storybook for React

Storybook is an open-source tool for building UI components and pages in isolation. It streamlines UI development, testing, and documentation.

Prerequisites

We will be using React project created in the simplest way, by using create-react-app with the Typescript template:

npx create-react-app my-app –template typescript

 

 NOTE: Storybook needs to be installed into a project that is already setup with a framework. It will not work on an empty project.

Next, we will need to clean up our project from the CSS and SVG files, so it will be as simple as possible.

 

After the clean-up let’s run our project npx start so we could make sure that everything works as expected without any errors:

 

Nice, now we can start adding storybook to our project.

 

Install Storybook

Use the Storybook CLI to install it in a single command. Run this inside your existing project’s root directory:

# Add Storybook:

npx storybook init 

After command execution you will notice four differences:

  • .storybook folder with the configuration files
  • stories folder inside the src folder with the examples;
  • updated json file with the scripts and dependencies;
  • updated yarn.lock after yarn install command that will be executed automatically;

 

Depending on your framework, first, build your app and then check that everything worked by running:

npm run storybook

 

It will start Storybook locally and output the address. Depending on your system configuration, it will automatically open the address in a new browser tab, and you’ll be greeted by a welcome screen.

After that, you can open the Storybook’s default page localhost: 6006

http://localhost:6006/?path=/story/example-introduction–page

 

You can change a port value in the “storybook” script:

 

NOTE: Sometimes after adding Storybook v6 version to your React v17 project you get an error on running React app npm start:

 

It can be easily fixed by adding “resolutions” to package.json file and reinstalling dependencies:

resolutions“: {
“@storybook/react/babel-loader”: “8.1.0”
},

OR

 

resolutions“: {
“babel-loader”: “8.1.0”
},

 

Stories

Let’s create our first Storybook story. We will not create any component inside the /src folder, we will create our custom components inside the .stories file:

NOTE: Exported component First will be rendered by Storybook UI.

 

As you can see it is very simple to create a Storybook page with your components.

You can use a Template approach with the same result. Templates approach could make your life easier when you need to define multiple components with different props:

Result will be the same:

 

NOTE: Let’s split our title for more sub-titles and see what will happen:

export default {
component: First,
title: ‘Hello/World/Components/First-2’,
} as Meta;

  reference: Storybook: Frontend workshop for UI development