search
HomeWeb Front-endJS TutorialReact Storybook: Develop Beautiful User Interfaces with Ease

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:

//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>);
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.

//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>);
import { configure } from '@kadira/storybook';

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

configure(loadStories, module);

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:

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
);

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:

import React from 'react';
import './Name.css';

const Name = (props) => (
  <div className={`name ${props.type}`}> {props.name} </div>
);

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

export default Name;

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:

.name {
  display: inline-block;
  font-size: 1.4em;
  background: #4169e1;
  color: #fff;
  border-radius: 4px;
  padding: 4px 10px;
}

.highlight {
  background: #dc143c;
}

.disabled {
  background: #999;
}

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
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function