Home >Web Front-end >JS Tutorial >React Storybook: Develop Beautiful User Interfaces with Ease

React Storybook: Develop Beautiful User Interfaces with Ease

Jennifer Aniston
Jennifer AnistonOriginal
2025-02-17 08:59:111030browse

React Storybook: Develop Beautiful User Interfaces with Ease

React Storybook: Develop Beautiful User Interfaces with Ease

At the beginning of a front-end project, a beautiful interface is usually designed first. You carefully plan and draw all UI components and their various states and effects. However, things tend to change during development. New demands and unforeseen use cases are emerging one after another. The initially beautiful library of components doesn’t cover all of these needs, you need to keep adding new designs.

If you have design experts around you at this time, it is great, but they often have switched to other projects, leaving developers alone to deal with these changes. As a result, design consistency begins to decline. It is difficult to track existing components in the component library, their status and appearance.

To avoid this design confusion, it is usually best to create separate documents for all components. While there are a variety of tools available for this purpose, this article will focus on a React Storybook, a tool designed specifically for React applications. It allows you to easily browse a collection of components and their functions. The React Native component library is an example of such an application.

Key Points

  • Simplify UI development: React Storybook simplifies the development and management process of UI components, allowing developers to build components independently and visualize their behavior in real time.
  • Enhanced Collaboration: It serves as a collaboration platform that bridges the gap between designers, developers and other stakeholders by providing a single location to view and interact with all UI components.
  • Customizable and scalable: Provides a wide range of customization options with add-ons and configuration settings, enabling developers to customize tools to their specific project needs.
  • Supports automated testing: Integrates with Jest and other testing frameworks to facilitate direct automated testing in the UI component development environment.
  • Widely versatile and scalable: Suitable for small and large projects, and supports other JavaScript frameworks other than React, making it a versatile choice for a variety of development teams.

Why do you need a React Storybook?

So, how can this display help? To answer this question, let's try to list the people involved in UI component development and evaluate their needs. Depending on your workflow, this list may vary, but usually includes the following:

Designer or UX expert

Responsible for the appearance and feel of the user interface. After the project prototype phase is completed, the designer usually leaves the team. When new requirements arise, they need to quickly understand the current state of the UI.

Developer

Developers are the ones who create these components and may be the main beneficiaries of the style guide. Developers have two main use cases: being able to find the right components from the library and test them during development.

Tester

The tester will carefully check that the components are implemented as expected. One of the main jobs of testers is to make sure the components work correctly in every aspect. While this does not eliminate the need for integration testing, it is usually more convenient than doing it alone in the project itself.

Product owner

Receives the design and implementation personnel. The product owner needs to make sure that every part of the project is in line with expectations and that the brand style is consistent.

You may have noticed that what all involved people are in common is having a single location with all components. Finding all components in the project itself can be very tedious. Think about it, how long does it take to find all possible button variants in the project (including their status (disabled, primary, secondary, etc.)? Therefore, having a separate library would be much more convenient.

If I've convinced you, let's see how to set up a Storybook in your project.

Set React Storybook

To set up a React Storybook, you first need a React project. If you don't have a suitable project at the moment, you can easily create one with create-react-app.

To generate a Storybook, please install getttorybook globally:

<code>npm i -g getstorybook</code>

Then navigate to your project and run:

<code>getstorybook</code>

This command will perform the following three operations:

  • Install @kadira/storybook into your project.
  • Add storybook and build-storybook scripts to your package.json file.
  • Create a .storybook folder with basic configuration and a stories folder with sample components and stories.

To run Storybook, execute npm run storybook and open the displayed address (https://www.php.cn/link/93e4d7106625e1b0f2eb8af065c83452:

React Storybook: Develop Beautiful User Interfaces with Ease

Add new content

Now that we have the React Storybook running, let's see how to add new content. Each new page is added by creating a story. These are snippets of code that render the component. The sample story generated by gettstorybook is shown below:

<code class="language-javascript">//src/stories/index.js

import React from 'react';
import { storiesOf, action, linkTo } from '@kadira/storybook';
import Button from './Button';
import Welcome from './Welcome';

storiesOf('Welcome', module)
  .add('to Storybook', () => (
    <welcome showapp="{linkTo('Button')}/">
  ));

storiesOf('Button', module)
  .add('with text', () => <button>Hello Button</button>)
  .add('with some emoji', () => <button>? ? ? ?</button>);</welcome></code>
The

storiesOf function creates a new part in the navigation menu, and the add method creates a new sub-part. You can organize your Storybooks at will, but you cannot create hierarchies that exceed two levels. One straightforward way to organize a Storybook is to create common top-level sections for related element groups, such as "form input", "navigation", or "widgets", and sub-parts of individual components.

You can freely choose where to place the story file: in a separate stories folder or next to the components. I personally prefer the latter because putting stories with components helps keep them accessible and up-to-date.

Stories are loaded in the .storybook/config.js file, which contains the following code:

<code>npm i -g getstorybook</code>

By default, it loads the src/stories/index.js file and expects you to import your story there. This is a little inconvenient because it requires us to import every new story we create. We can modify this script to automatically load all stories using Webpack's require.context method. To distinguish story files from the rest of the code, we can convention to add .stories.js extension to them. The modified script should look like this:

<code>getstorybook</code>

If you are using a different folder as source code, make sure to point it to the correct location. Rerun Storybook to make the changes take effect. The Storybook will be empty because it no longer imports the index.js file, but we will solve this problem soon.

(The following content is basically consistent with the original text, and make a little adjustment to keep the semantics unchanged, and partial descriptions are simplified)

Writing a new story

Now that we have slightly tweaked the Storybook to suit our needs, let's write our first story. But first we need to create a component to show. Let's create a simple Name component that displays the name in a colored block. This component will have the following JavaScript and CSS.

<code class="language-javascript">//src/stories/index.js

import React from 'react';
import { storiesOf, action, linkTo } from '@kadira/storybook';
import Button from './Button';
import Welcome from './Welcome';

storiesOf('Welcome', module)
  .add('to Storybook', () => (
    <welcome showapp="{linkTo('Button')}/">
  ));

storiesOf('Button', module)
  .add('with text', () => <button>Hello Button</button>)
  .add('with some emoji', () => <button>? ? ? ?</button>);</welcome></code>
<code class="language-javascript">import { configure } from '@kadira/storybook';

function loadStories() {
  require('../src/stories');
}

configure(loadStories, module);</code>

You may have noticed that this simple component can have three states: default, highlighted, and disabled. Wouldn't it be nice to visualize all of these states? Let's write a story for this. Create a new Name.stories.js file next to your component and add the following:

<code class="language-javascript">import { configure, addDecorator } from '@kadira/storybook';
import React from 'react';

configure(() => {
    const req = require.context('../src', true, /.stories\.js$/);
    req.keys().forEach(filename => req(filename));
  },
  module
);</code>

Open Storybook and view your new components. The results should be as follows:

React Storybook: Develop Beautiful User Interfaces with Ease

Feel free to change how the component is displayed and its source code. Note that due to React's hot reloading feature, changes appear immediately in your Storybook whenever you edit a story or component, without manually refreshing the browser. However, when you add or delete files, refresh may be required. Storybooks don't always notice these changes.

(The following content is also streamlined and adjusted to maintain semantic consistency)

View customization

If you want to change how the story is displayed, you can wrap it in a container. This can be done using the addDecorator function. For example, you could add a "example" title to all pages by adding the following code to .storybook/config.js:

<code class="language-javascript">import React from 'react';
import './Name.css';

const Name = (props) => (
  <div classname="{`name"> {props.name} </div>
);

Name.propTypes = {
  type: React.PropTypes.oneOf(['highlight', 'disabled']),
};

export default Name;</code>

You can also customize separate parts by calling addDecorator after storiesOf.

Posted your Storybook

Once you have done your Storybook's work and think it's ready to be published, you can build it as a static website by running:

<code class="language-css">.name {
  display: inline-block;
  font-size: 1.4em;
  background: #4169e1;
  color: #fff;
  border-radius: 4px;
  padding: 4px 10px;
}

.highlight {
  background: #dc143c;
}

.disabled {
  background: #999;
}</code>

By default, Storybook is built into the storybook-static folder. You can change the output directory using the -o parameter. Now you just need to upload it to your favorite hosting platform.

If you are working on a project on GitHub, you can publish your Storybook by building it into the docs folder and pushing it to the repository. GitHub can be configured to provide your GitHub Pages website from there. If you don't want to save the built Storybook in the repository, you can also use storybook-deployer.

Build configuration

Storybook is configured to support many features in the story. You can write it in the same ES2015 syntax as create-react-app, however, if your project uses a different Babel configuration, it will automatically pick up your .babelrc file. You can also import JSON files and images.

If you think this is not enough, you can add additional webpack configuration by creating a webpack.config.js file in the .storybook folder. The configuration options exported by this file will be merged with the default configuration. For example, to add support for SCSS to your story, just add the following code:

<code>npm i -g getstorybook</code>

Don't forget to install sass-loader and node-sass.

You can add any required webpack configuration, however, you cannot override the entry, output, and the first Babel loader.

If you want to add different configurations for development and production environments, you can export a function. It will be called using the basic configuration and the configType variable set to "DEVELOPMENT" or "PRODUCTION".

Extend functionality with add-ons

Storybook itself is very useful, but to make it better, it has some add-ons. In this article, we're only covering some of them, but be sure to check out the official list later.

(The following parts are streamlined and the introduction of addon is adjusted)

Storybook comes with two preconfigured add-ons: Actions and Links. You don't need to make any additional configuration to use them.

  • Actions: Allows you to log component-triggered events in the Action Logger panel.
  • Links: Allows you to add navigation between components.

Knobs: Allows you to customize components by modifying React properties directly from the UI at runtime. Installation method: npm i --save-dev @storybook/addon-knobs, registration method: import in .storybook/addons.js. Use the withKnobs decorator to wrap the story.

Info: Allows you to add more information about the story, such as its source code, description, and React propTypes. Installation method: npm i --save-dev @storybook/addon-info, registration method: Use .storybook/preview.js in addDecorator.

Automatic testing

An important aspect of Storybook (not described in this article) is to use it as a platform for running automated tests. You can perform a variety of tests, from unit tests to functional tests and visual regression tests. As expected, there are some add-ons designed to enhance the functionality of Storybook as a test platform. We won't go into details as they deserve separate articles, but still want to mention them.

  • Specifications: Allows you to write unit tests directly in the story file.
  • Storyshots: Allows you to perform Jest snapshot tests based on the story.

Storybook as a service

Kadira also offers Storybook as a service called Storybook Hub. It allows you to host Storybooks on it and take collaboration to the next level. In addition to standard features, it integrates with GitHub and can generate a new Storybook for each of your pull requests. You can also leave a comment directly in Storybook to discuss changes with your colleagues.

Conclusion

If you feel that maintaining UI components in your project is starting to get painful, take a step back and see what you're missing. You may just need a convenient collaboration platform between all parties involved. In this case, for your React project, Storybook is the perfect tool for you.

Are you already using a Storybook? Are you planning to give it a try? Why? Or why not? I'd love to hear you in the comments.

(FAQ part is streamlined and the structure is adjusted)

FAQ (FAQ)

  • How is React Storybook different from other UI development tools? React Storybook allows developers to build components independently, making the development process faster and more efficient, and provides a real-time visual testing environment.
  • Can I use React Storybook in other JavaScript frameworks? Yes, it supports frameworks like Vue.js and Angular.
  • How to add add-ons to my Storybook? Install via npm or yarn, add to the .storybook/addons.js file, and configure it according to the documentation.
  • What is the learning curve of React Storybook? If you are familiar with JavaScript and React, you should be able to get started soon.
  • Can I use React Storybook for large projects? Yes, it is used by large organizations such as Airbnb, IBM and Lyft.
  • How to share my Storybook with others? It can be deployed to static managed services such as GitHub Pages or Netlify using Storybook Deployer.
  • Can I test my components in React Storybook? Yes, it provides a visual test environment and can be integrated with test libraries such as Jest.
  • How to customize the appearance of a Storybook? Storybook provides options such as theme customization, custom webpack configuration, and creating custom add-ons.
  • Can I use React Storybook for mobile application development? Yes, it supports React Native.
  • Is React Storybook open source? Yes, it is hosted on GitHub and welcomes contributions from developers around the world.

In short, the original text was greatly rewritten to make it more concise and smooth, and maintained the original meaning. The image format remains the same.

The above is the detailed content of React Storybook: Develop Beautiful User Interfaces with Ease. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn