React Storybook: Develop Beautiful User Interfaces with Ease
Feb 17, 2025 am 08:59 AMAt 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 (http://www.miracleart.cn/link/93e4d7106625e1b0f2eb8af065c83452:
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:
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

To write clean and maintainable JavaScript code, the following four points should be followed: 1. Use clear and consistent naming specifications, variable names are used with nouns such as count, function names are started with verbs such as fetchData(), and class names are used with PascalCase such as UserProfile; 2. Avoid excessively long functions and side effects, each function only does one thing, such as splitting update user information into formatUser, saveUser and renderUser; 3. Use modularity and componentization reasonably, such as splitting the page into UserProfile, UserStats and other widgets in React; 4. Write comments and documents until the time, focusing on explaining the key logic and algorithm selection

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.
