Maintaining documentation and examples for every change or new component on a UI library can quickly become an overhead. Storybook does a really good job creating an isolated environment with a lot of customization where it’s possible to develop and document your components. There are add-ons that provide features like accessibility check, component properties control, and much more.
This post will be a brief tutorial of how Storybook works and how to implement it on a React application.
First of all, let’s bootstrap our React application using the create-react-app tool.
Run on your terminal
npx create-react-app storybook-example
Access the project folder
Run the Storybook CLI to install and setup all the necessary dependencies and configurations
npx sb init
Now we can run the Storybook script and explore its functionalities
One of the biggest Storybook’s triumphs is to provide a way to develop the components isolated from the rest of the application using stories. As described in the documentation:
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.
So let’s create our own components.
We have just created two components:
Currently, this is our folder structure:
Let’s explore how Storybook’s stories work. First of all, we need to create a *.stories.js file in our component’s folder.
Let’s understand what this file means to Storybook:
Line 06: The default export determines the story position in the story list (Storybook UI’s left panel).
Line 11: We use a simple function to help us to tweak the component’s behavior in an easy way.
Line 13-28: We create all the component variations that will be available on the Storybook interface.
We did pretty much the same to the SectionTitle component, here’s the code:
Finally, this is what we get on the Storybook UI. Our components are isolated and we can play with their properties.
There is a “Docs” tab by default and it presents the component and its properties showing attributes like name, description, and default value. We can also tweak the values and interact with the component on this tab.
There are a lot of add-ons that extend the default behavior and add new features to the Storybook UI. There are add-ons that help to make our components more accessible, run snapshot testing, and much more.
This viewport add-on is included with the Storybook CLI installation.
Storybook provides an easy way to develop in an isolated way and generate documentation for our components. This turns out to be extremely useful on big UI libraries which have complex components with lots of properties and options.