Location>code7788 >text

Front-end art practice: Building interactive component documents with Storybook

Popularity:101 ℃/2025-04-14 07:48:21

For the front-end, component conversations have changed from hot topics to basic capabilities, and custom components or self-built component libraries are now common. In actual work, the documentation of the component library directly determines the development experience and efficiency, and the importance of document construction is self-evident. The tool I want to recommend today is Storybook, for this I specially passedBuild a CI/CD system with a server I bought for 99 yuanDeploy a set of demos, welcome to click to experience:Demo(The first loading speed is particularly touching, please wait patiently. It is only used for effect demonstration, I hope everyone will not be confused by this sloppy demo). The documentation of the component library is not just a "write description", but also visual, interactive, and reusable - it can be viewed, clicked, and copied directly. Among the document tools that can meet these needs, the following two are recommended:DumiandStorybook

Dumi


Dumi is a static site framework created for component development scenarios. It has a representative work:Ant Design. I don't know if anyone is like me, but the first thing I see is not Ant Design's component, but its component library documentation. I am really jealous of their document, which has cases, codes, interactions, and detailed parameter descriptions. If you are interested in it, clickDumi Portal

Storybook


Storybook is an open source project with 83K+ stars already on GitHub. It is not only used to build component library documents, but also to test components. The main reasons for recommending Storybooks are as follows:

  1. It can be directly embedded in the project, and component encoding and testing is performed while writing component documents;
  2. Automatically generate component parameter documents based on TypeScript component type definition;
  3. Allows dynamically modify component parameter values ​​in the document and preview different effects in real time
  4. It is difficult to build basic documents (mostlyDemoThe document was written for no more than 1 minute, mainly due to my projectNebula Note, can realize quick content replacement).
  5. Third-party libraries can be used in the document to enrich the document effects, such as: Swiper, Mermaid, MathJax, etc.
  6. Supports multiple frameworks (React, Vue, Angular, etc.) and supports multiple languages ​​(TypeScript, JavaScript, HTML, CSS, etc.).

Install


1. Run the following command in the root directory of the project. Storybook will automatically detect your framework (React, Vue, Angular, etc.) and install it accordingly:

npx storybook@latest init

The installation process may take several minutes, and when it is finished it adds the necessary Storybook dependencies and generates the .storybook configuration directory and then creates the sample components in the src/stories/ directory.


run


npm run storybook

By default, Storybook will be inhttp://localhost:6006/run. Although we didn't write a single line of code, we can already see the sample component documentation provided by Storybook.


Configuration


Before writing a document, you should first decide how to store the document:

  • Centralized storage:Put all documents in a specified directory, such as src/stories/, similar to the management method of sample documents.
  1. Advantages: clear structure, decoupling of documents and business code, convenient for unified management.
  2. Applicable scenarios: suitable for large-scale component library development, especially projects that require independent maintenance of documents.
  • Follow the component:The Story documentation for each component is stored with component code, such as src/components/Button/.
  1. Advantages: Documents are closely connected to components, easy to develop and maintain, and do not need to jump between multiple directories.
  2. Applicable scenarios: suitable for product-type projects, component documents are updated with component code and kept in synchronization.

If you choose to follow the component, you need to adjust the .storybook/ (or ) and specify the document path. The sample code is as follows:


const config: StorybookConfig = {
    stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],

Hello World


Let's share a React version example first. Create a new document, The content is as follows:

import { Meta, StoryObj } from '@storybook/react';
 import Button, { ButtonProps } from './index';
 import { action } from '@storybook/addon-actions';

 export default {
     title: 'Atoms/Button', // Component grouping and display paths in Storybook.  `'Atoms/Button'` means that the component will be displayed as `Button` under the `Atoms` group.
     component: Button, // Associated React component
     tags: ['autodocs'], // `'autodocs'` means to enable automatic document generation
     argTypes: {}, // Define the control type, classification, description, etc. of component props
     args: {}, // Set the default props value for the component, shared in all stories, and can be modified in the UI panel
 } as Meta<ButtonProps>;

 export type Story = StoryObj<ButtonProps>;
 export const Primary: Story = {
   // Specify the props value of the component running, which can be modified in the UI panel
     args: {
         children: 'Button',
         type: 'primary',
         onClick: action('Button clicked'),
     },
 };

The above is a complete button documentation code. In stories in Storybook, actions can be used to listen for button click events.action('Button clicked')Event calls and parameters can be displayed in real time on the Action panel, which is very friendly to component self-test and can help developers quickly verify component interactive behavior.


Show off the original exclusive document effect (not pictures, you can click to experience):

Effect previewComplete Demo

Add interactive logic: Make components move


To make the document more vivid and intuitive, we will add some examples of component with interaction or state. Since it is written in Storybook almost the same as normal development, we need to change the file suffix to .tsx to support JSX and types. First, here is the sample codeDemomiddleDropdownDocument code snippets for component search function:

import React, { useEffect } from 'react';
 import { useArgs } from '@storybook/preview-api';
 // The code related to component document definition is omitted here
 ......
 export const Primary: Story = {
     args: {
         enableTags: [
             {
                 tag: 'two',
                 color: '#ff0000',
             },
             {
                 tag: 'four',
                 color: 'orange',
             },
         ],
         options: [],
     },
     render: () => {
         const options = [
             {
                 value: '1',
                 label: 'Option one',
                 keyword: '1',
             },
             {
                 value: '2',
                 label: 'Option two',
                 keyword: '2',
             },
             {
                 value: '3',
                 label: 'Option three',
                 keyword: '3',
             },
             {
                 value: '4',
                 label: 'Option four',
                 keyword: '4',
             },
         ];
         const [args, updateArgs] = useArgs<DropdownProps<string>>();
         useEffect(() => {
             updateArgs({ options: options });
         }, []);
         const handleSearch = (keyword?: string) => {
             if (keyword) {
                 const newOptions = ((option) =>
                     ?.includes(keyword),
                 );
                 updateArgs({ options: newOptions });
             } else {
                 updateArgs({ options: options });
             }
         };

         return <Dropdown {...args} onSearch={handleSearch} />;
     },
 };

Because Dropdown is a controlled component, Storybook is used hereuseArgsThe purpose of this hooks is to update the results to the parameter panel. As can be seen from the code snippet, Storybook supports us to add arenderFunctions to implement custom document logic and effects,renderWe can use it normally in the functionReactfunction.

Effect previewComplete Demo

Rich document content: automatic generation vs manual editing


existStorybookThere are two ways to add rich pictures and text introductions to the document:

  • useAutodocsAutomatically generated basic template, configured through MetaProperties, add introduction content to components;
  • useMDXCreate a custom document page for each component.

Autodocs

Autodocs is a feature of Storybook that readsMetamiddleThe attribute content automatically generates component documents. The document generated by Autodocs will prioritize the content of the first example (Primary) and the component's Props list, and then display all the Story in turn. like:

Multiple Story examplesComplete Demo

Autodocs is very simple to use, just like in the above case, justexport defaultAdded to the content of tags: ['autodocs'],Just (Jump to Hello WorldView the code).


MDX

MDX is a powerful feature provided by Storybook, which allows us to use both Markdown and JSX in documents (Vue users can also use the corresponding syntax), creating a more flexible and controllable component documentation experience. With MDX, we can not only write captions like we do on a blog, but also embed component instances, add interactive examples, introduce custom styles and layouts, and even encapsulate document templates to reuse common structures.

Compared with Storybook's Autodocs (auto-generated parameters + interactive pages), MDX provides complete content dominance, and we can freely decide the structure, order and style of the document: for example, first talk about the background, then display components, finally talk about parameters, or combine multiple components into scene-based example pages without being restricted by the automatic document generation logic.

This approach is particularly suitable for scenarios where you need to explain the context, build complex interactive examples, or conduct teaching documents. It makes component documents not only "available", but also "telling and demonstrating", truly realizing the integration of documents and design and development.


at last


Component documentation is not an add-on, but a standard configuration for component libraries. Storybook not only can write documents, but also supports component automation testing, which is really both playable and easy to use. If you haven't tried it, it is highly recommended to try it yourself!

I have compiled and published some of the Storybook-related documents on my personal website () Welcome to check it out.

Thank you for reading. If you think it is good, please like and support~✌️