12.8 C
New York
Saturday, January 13, 2024

Scale Your React App with Storybook and Chromatic — SitePoint


This text explains how one can combine Storybook and Chromatic to scale your React utility’s element library and profit from clear documentation, visible regression testing and crew effectivity.

Desk of Contents

Why Use Storybook?

Storybook is a useful instrument for engineers, product house owners and stakeholders alike. Storybook permits frontend engineering groups to construct element libraries to facilitate collaboration and forestall the event of parts from being blocked by extra vital venture structure choices.

It acts as a standalone utility inside your extra in depth venture that may doc parts and their variations. Storybook comes full of a ton of options which will be personalized and configured to your liking. Beneath are a few of the options I exploit on on a regular basis initiatives:

  • net accessibility audits
  • unit, interplay and snapshot testing
  • doc element performance for engineers and stakeholders
  • simple publishing and internet hosting
  • integration with Chromatic for visible regression testing (VRT)

This text explores putting in and configuring Storybook in a pattern Create React App venture, putting in add-ons, writing tales, producing automated documentation and publishing your Storybook to the Net.

Setting Up and Configuring Storybook

Let’s first have a look at set up.

Putting in Storybook

Storybook was developed to suit right into a plethora of various venture sorts. The simplest solution to get began with Storybook is to put in it right into a pre-existing utility and run a easy command on the root of your venture:

npx storybook@newest init

The above command will have a look at your venture dependencies and decide probably the most acceptable solution to set up Storybook.

If you happen to need assistance figuring out whether or not your venture would help Storybook, learn by the Frameworks web page within the documentation.

Word: you possibly can set up Storybook manually, however this usually leads to errors and mismanaged dependencies, which may trigger issues.

Configuring Storybook

One of many extra complicated features of Storybook is configuring it to align with applied sciences current in your utility. Additional customization can be required to make sure Storybook behaves in a way aligned together with your utility’s expertise stack.

Configuring Storybook is primarily accomplished by the foremost.js file. You’ll be able to specify all the things right here — from how documentation is offered, to extending Storybook’s UI with add-ons. You’ll be able to even prolong Webpack.

Storybook helps TypeScript out of the field, however it’s essential to arrange your CSS structure. Many flavors of CSS are supported. Yow will discover extra data within the Styling and CSS documentation.

Let’s spin up a Create React App occasion:

npx create-react-app my-scalable-component-library

The above command will bootstrap a primary React utility. We’ll be utilizing Create React App for this text, although different frameworks are additionally supported. Let’s make certain your utility is working accurately by operating npm run begin. It’s best to see one thing much like what’s pictured under.

A screenshot of Create React Apps initial screen

Let’s set up Storybook subsequent. Run the next line within the root of your utility:

npx storybook@newest init

The script will do a little bit of pondering after which immediate you to substantiate just a few particulars. Storybook is sensible sufficient to detect that we’re utilizing Create React App (CRA), and it’ll possible must replace just a few dependencies to work seamlessly together with your venture. Hit Y if you see the immediate pictured under.

A screenshot of the output of running Storybook for the first time

If all goes in response to plan, Storybook will launch in your browser, and also you’ll see what’s pictured under.

A screenshot of a successfully installed Storybook in the browser

At this level, it’s price what’s modified in our venture. Storybook added a .storybook folder the place your configuration recordsdata reside. You’ll additionally discover a tales folder added to the src listing. There are usually three associated recordsdata for every “story”. We’ll uncover that in additional element a bit later.

Each the bundle.json and package-lock.json have been up to date. Updates to those recordsdata pertain primarily to dependencies, however bundle.json additionally has two new scripts:

"storybook": "storybook dev -p 6006",
"build-storybook": "storybook construct"

Run npm run storybook to spin up a dev surroundings and npm run build-storybook if you’re able to publish your first Storybook.

Let’s run npm run build-storybook. The output is a folder referred to as storybook-static: it is a “revealed” Storybook that may be made publicly accessible.

At this level, Storybook and CRA are totally arrange. Chances are you’ll wish to add the storybook-static folder to your .gitignore in case you don’t plan to trace the static recordsdata.

It’s additionally price noting {that a} handful of parts have been added to your listing. You’ll be able to take away them if want be. Nevertheless, I like to recommend maintaining them for reference, if for nothing else. Earlier than we transfer on, let’s briefly check out foremost.js:


const config = {
  tales: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|mjs|ts|tsx)"],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/preset-create-react-app",
    "@storybook/addon-onboarding",
    "@storybook/addon-interactions",
  ],
  framework: {
    identify: "@storybook/react-webpack5",
    choices: {},
  },
  docs: {
    autodocs: "tag",
  },
  statistics: ["../public"],
};
export default config;

There are just a few important elements to this file. Firstly, the tales key tells the Storybook the place to search for element tales. As you replace your file/folder structure in CRA, replace these paths to keep away from shedding your tales in Storybook.

framework is usually totally different for every venture kind. docs tells Storybook to doc parts mechanically.

I’d extremely advocate studying the Configure web page within the Storybook docs for extra details about what will be dealt with by foremost.js.

Deciding on Storybook Add-ons

You’ll be able to consider Storybook add-ons as “plugins”. They’re pre-written packages that stretch the core Storybook APIs and carry out duties like integrating JS/CSS frameworks or enhancing the default conduct of Storybook.

What add-ons you put in will rely in your venture and your crew’s targets. There are successfully two kinds of add-ons: UI-based and preset-based. “UI-based” add-ons customise the purposeful look of Storybook. “Preset-based” add-ons permit you to combine with different applied sciences like TypeScript or Tailwind. Yow will discover a group of all add-ons on the Integrations web page.

Word: some add-ons are maintained by the Storybook crew, whereas others are community-driven. Neighborhood-driven add-ons might yield surprising outcomes or might not be suitable with the most recent model of Storybook.

Earlier than you go on the hunt for a group of add-ons you are feeling can be greatest to combine, ensure you check out what Storybook installs by default:

addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/preset-create-react-app",
    "@storybook/addon-onboarding",
    "@storybook/addon-interactions",
  ],
  1. @storybook/addon-links enables you to hyperlink Tales to construct prototypes.
  2. @storybook/addon-essentials embody all add-ons situated right here: https://storybook.js.org/integrations/tag/necessities/.
  3. @storybook/preset-create-react-app is a preset-based add-on that enhances the mixing with CRA.
  4. @storybook/addon-onboarding gives a guided tour of Storybook options.
  5. @storybook/addon-interactions means that you can debug the interplay state of your parts. If you happen to’re , you possibly can learn extra about Interplay assessments.

Let’s say you wish to add one other add-on to your configuration. Let’s set up the Accessibility add-on:

npm set up @Storybook/addon-a11y

Subsequent, we have to inform Storybook to initialize the add-on. This may be accomplished by including the add-on to the addons key in foremost.js:

addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "@storybook/preset-create-react-app",
    "@storybook/addon-onboarding",
    "@storybook/addon-interactions",
    "@storybook/addon-a11y",
  ],

Save foremost.js, after which let’s boot up Storybook once more by operating npm run storybook.

A screenshot of the newly added Accessibility panel

You’ll be able to see now that the “Accessibility” tab has been added to all story situations and is already flagging issues with a11y in our parts. “UI-based” add-ons solely require just a little configuration. “Preset-based” will be extra complicated. The rationale for that is that “preset-based” add-ons typically want additional configuration, reminiscent of:

  • inserting configuration recordsdata on the root of your venture
  • configuring choices / Webpack configurations that should align together with your CRA utility settings

This will trigger quite a lot of friction, and remediation can depend upon the framework of selection. Use warning when extending Storybook with “preset-based” add-ons and guarantee parity together with your utility.

Writing and Documenting Element Tales

It’s now time to write down tales. A narrative in Storybook is normally tied to a element and its variations. Tales are extremely dynamic recordsdata written in React, Markdown, or a mix of each applied sciences. Tales are handed parameters that align with props the React element accepts.

These props will be configured to output variations of every element. This enables engineers to work together with prop values inside the Storybook UI. Let’s evaluation our Button story that was added by our bootstrapping of Storybook:

import { Button } from './Button';

export default {
  title: 'Instance/Button',
  element: Button,
  parameters: {
    format: 'centered',
  },
  tags: ['autodocs'],
  argTypes: {
    background-color: { management: 'shade' },
  },
};

export const Main = {
  args: {
    major: true,
    label: 'Button',
  },
};

export const Secondary = {
  args: {
    label: 'Button',
  },
};

export const Massive = {
  args: {
    dimension: 'massive',
    label: 'Button',
  },
};

export const Small = {
  args: {
    dimension: 'small',
    label: 'Button',
  },
};

The above illustrates the format you possibly can observe when making a Story. There should at all times be a default export. That is the principle element. It’s the place important settings are configured. Most of them are self-explanatory. Nevertheless, I wish to name out the next:

  • Parameters are a set of static, named metadata a few story, sometimes used to manage the conduct of Storybook options and add-ons.
  • Tags will auto-generate documentation for every element story. Learn extra about AutoDocs.
  • argTypes specify the conduct of args or annotate args. Learn extra about archetypes.

Any named export after the preliminary default export is a variation. Every variation is an object with an args key. args on this context ought to align with the props handed to your element. Every variation can be output in Storybook underneath the Button element, and you’ll work together with them as wanted.

Understanding Decorators goes a great distance in case you plan on constructing extra complicated tales. A decorator gives a solution to wrap tales in additional context and performance. Tales will be handed to a decorator by setting the decorator key within the story parameters:

decorators: [
    (Story) => (
      <div style={{ margin: '3em' }}>
        {}
        <Story />
      </div>
    ),
  ],

Within the instance above, we add a <div> that wraps our element, and we assign it 3em of margin.

Tales may eat parts from different Tales. Simply be conscious that it will depend on how your element renders and the way a lot element you intend on including to your utility general.

Within the Storybook docs, you possibly can examine Sub Elements intimately.

Writing a Story for our utility

Let’s put this all to the take a look at. We’re going so as to add a element to our utility referred to as Footer. It will require three recordsdata:

  • Footer.jsx
  • Footer.tales.js
  • footer.css

Create these recordsdata within the src/tales folder. Our Footer.jsx goes to be easy:

import React from 'react';
import PropTypes from 'prop-types';

export const Footer = ({ siteOwner, showCopyRight }) => (
  <footer>
    <div className="footer">
      {showCopyRight && (
        <div>
          <span>
            <span position="img" aria-label="copy">©️</span> 2018 {siteOwner}.
          </span>
        </div>
      )}
    </div>
  </footer>
);

Footer.propTypes = {
  siteOwner: PropTypes.string.isRequired,
  showCopyRight: PropTypes.bool,
};

Footer.defaultProps = {
  showCopyRight: true,
};

It takes two props: siteOwner and showCopyRight. Subsequent up, let’s write a narrative for the Footer:

import { Footer } from './Footer';

export default {
  title: 'Instance/Footer',
  element: Footer,
  tags: ['autodocs'],
  parameters: {
    format: 'fullscreen',
  },
};

export const WithSiteOwner = {
  args: {
    siteOwner: 'Jane Doe',
    showCopyRight: true,
  },
};

export const WithOutCopyRight = {
  args: {
    siteOwner: 'Jane Doe',
    showCopyRight: false,
  },
};

It is a comparatively contrived instance, but it surely illustrates how simple it’s so as to add a narrative. Add the above to Footer.tales.js. The consequence can be an auto-documented, multi-variant story that permits customers to work together with the element’s props.

A screenshot of the Footer story recently added to Storybook

Attempt updating the siteOwner worth instantly within the story controls. If you wish to model the Footer, import footer.css into Footer.jsx and reference the category names. If you happen to’re concerned about seeing how the element behaves in your React utility, import it:

import { Footer } from './tales/Footer';
...
<Footer siteOwner='Daine Mawer' showCopyRight />

Good! You’ve simply created your element and a corresponding story! Subsequent, we’ll talk about publishing your storybook on the Net.

Publishing Your Storybook

Engineers can simply view and develop regionally on Storybook, because the configuration is tracked by your most popular model management system. Nevertheless, a URL to entry the revealed Storybook can be way more manageable for non-technical stakeholders.

If you run a manufacturing construct of Storybook, its output is a group of static recordsdata which are outputted right into a construct folder. Fortunately, the Storybook crew has made this comparatively simple to realize. All you want to do is run this:

npm run build-storybook

The construct will terminate if it comes throughout any construct errors, so there’s no manner of publishing a damaged Storybook. Now that we’ve a manufacturing construct, we’d like someplace to host it.

There are a number of methods to do that: GitHub Pages, Netlify, and AWS S3. A few of these choices require extra configuration than others.

If you happen to don’t plan on establishing Chromatic (really useful), I like to recommend operating with GitHub Pages, as you possibly can add a GitHub Motion to make brief work of the configuration and setup.

Setting Up Chromatic for VRT

Chromatic is a strong instrument that lives alongside Storybook. The Storybook crew maintains Chromatic, so integrating the instrument into your pre-existing utility and CI requires minimal effort.

By integrating Chromatic, you possibly can make sure that visible regressions, even interplay bugs, don’t make it to your manufacturing surroundings. The applying permits for seamless collaboration inside groups and goes a protracted solution to guaranteeing bugs are caught early and infrequently.

What’s extra, Chromatic is free — with limitations, after all.

Let’s say we wish to combine Chromatic with our revealed Storybook. Join a Chromatic account and seize a Mission Token. Subsequent, you’ll want to put in the Chromatic npm bundle into your venture:

npm set up --save-dev chromatic

Then add a chromatic script to your bundle.json:

"scripts": {
    "chromatic": "chromatic"
}

You’ll then want to make sure that you may have a .env file with the next surroundings variable outlined: CHROMATIC_PROJECT_TOKEN. You’ll be able to add the Mission Token out of your Chromatic account as the worth.

Run npm run chromatic. It will publish your Storybook to your Chromatic venture. You’ll be able to then entry a formidable UI to evaluation parts and their modifications. The issue with this setup is that you simply’ll must run Chromatic every time you modify parts.

This can be okay for smaller initiatives, however committing modifications to your utility and having a CI pipeline deal with this difficult work is much better. Chromatic CI integrates instantly into pull requests.

If you happen to’re utilizing GitHub, you possibly can shortly stand up and operating with GitHub Actions by including a workflows folder to your .github listing. Observe the steps in Chromatic Docs outlined at Automate Chromatic with GitHub Actions to stand up and operating.

You could have now revealed a element library that runs UI Checks and Opinions every time you commit modifications to your parts.

Conclusion and Takeaways

Storybook and Chromatic instruments will empower your crew to ship higher-quality code. Use Storybook to automate and iterate in your shared element libraries.

Above all else, these two instruments will guarantee your engineering crew can develop in confidence, ship options and bug fixes extra effectively and be certain that your product is at all times well-documented, scalable and extensible.



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles