React Components Living Style Guides Overview
By Grzegorz Pawlik

For many years style guides have been in use as an primary platform of communication between designers and developers working on any complex project. Usually it’s been a separate resource that breaks down the user interface to organized building blocks and serve as a reference to locate and define design patterns for the project. The problem with this approach is that we have to maintain the code in two different places: the guide itself and the actual production codebase. And unfortunately the style guide consistency is the first to sacrifice when comes to hotfixes and tight deadlines.

To the rescue comes the concept of so-called living pattern libraries, where the components are being rendered using production code and enable interactivity and live configuration. This approach comes handy on every stage of the project and for anybody in a cross-functional team. Starting from designers who can easily catch up on the existing state of UI elements, through the developers and QAs who can can use it as a playground to develop, maintain and test their components in isolation, ending up with product owners who finally need to have a global overview on the design and implementation.

The bigger the team is, and the more complex the codebase is, the more beneficial it is to have one source of truth to reference when working and iterating over the UI components. It is specially true when it comes to modern frontend development, the React applications in first place, that can easily end up with hundreds or thousands of UI components and complex hierarchies.

Let’s have a look at some of the most interesting projects that provide the tools to easily create and configure living style guides out of your existing React codebase.

Storybook

Docs & demo: https://storybook.js.org/
Github: https://github.com/storybooks/storybook

Storybook style guide example

It is the most popular pattern library creation tool, gaining even more popularity since the release of version 3.0 which added support for Webpack 2.0 and snapshot testing. Initial setup is quite straightforward and consists in creation of definitions (stories) for each component with the corresponding state in a similar manner to the visual test cases:

import React from 'react';
import { storiesOf } from '@storybook/react';

import MyComponent from './MyComponent';

storiesOf('MyComponent', module)
  .add('default', () => <MyComponent />)
  .add('custom size', () => <MyComponent size="large" />);

Once the story is ready the next step is to define its path in the Storybook configuration file at .storybook/config.js:

import { configure } from '@storybook/react';

function loadStories() {
  require('../stories/index.js');
  // You can require as many stories as you need.
}

configure(loadStories, module);

The popularity of the Storybook comes from its powerful Addons that complement basic functionalities. The most significant are natively supported by the platform, e.g. Actions - to inspect events, Links - to bind the stories together or Knobs - to dynamically edit element props. Apart of that there are several useful community plugins that help with creating props combinations, internationalization, improving components organization, versioning, to name but a few. You can see the more complete list of available Addons and check the API reference here.

PROS:

  • Project maturity and active community
  • Straightforward to setup and maintain
  • Hot module reload (even for functional stateless components)
  • Support for React Native components, CSS, images and other static files
  • Allows to inspect events related to your components
  • Allows to edit React props dynamically using the Storybook UI
  • Integrates Jest snapshot testing for all stories
  • Possibility to further customization via Addons API

CONS:

  • Missing support for deeper level hierarchy by default

React-styleguideist

Docs: https://react-styleguidist.js.org/
Demo: https://react-styleguidist.js.org/examples/basic/
GitHub: https://github.com/styleguidist/react-styleguidist

React Styleguidist style guide example

Styleguidist needs even less initial configuration since it directly parses the source files (using react-docgen) and generates documentation based on PropTypes or Flow annotations. Styleguidist uses Markdown for specific components definition and by default searches for and parses the Readme.md or ComponentName.md files in the component’s folder. Typical element definition can look as simple as this:

```
<MyComponent size="large" />

Furthermore the library supports JSDoc tags when documenting components (e.g. @author, @version, @deprecated), which in combination with proper comments and propTypes declarations can help with providing as much complete information as possible:

/**
 * The component description
 *
 * @version 1.0.1
*/
class MyComponent extends Component {
  static propTypes = {
    /**
     * The color for the component
     */
    color: PropTypes.string,
    /**
     * The size of the component
     *
     * @since Version 1.0.1
     */
    size: PropTypes.oneOf(['small', 'normal', 'large'])
  };
  ...
}

All the other custom configuration can be defined in the styleguide.config.js file, which can include specific categories and sections, third-party libraries integrations, custom component path pattern (other than default src/@(components|Components)/**/*.{js,jsx}) or easy to setup visual customization and theming.

PROS:

  • Automatically finds components definitions
  • Hot module reload
  • Ability to switch between general components view and their isolated scopes
  • Clear overview of the components props, including their default values and description
  • Easy to exclude unwanted props or control which methods have to be visible in the documentation
  • Support for JSDoc tags when documenting components
  • Support for such libraries as Redux, Relay, styled components and CSS modules

CONS:

  • Missing option to live change component props

BlueKit

Docs: http://bluekit.blueberry.io/
Demo: http://bluekit.blueberry.io/demo
GitHub: https://github.com/blueberryapps/react-bluekit

BlueKit style guide example

This tool’s most powerful feature is a robust live preview with editable source. It not only creates dynamically the components library from the specified path, but analyzes all the information included in the propTypes and generates a set of UI controls to ease props manipulation respectively to its type. The library configuration is being stored automatically in the componentsIndex.js file on the root of the project that you reference from any route in your application to display the documentation:

import React, { Component } from 'react';
import BlueKit from 'react-bluekit';
import componentsIndex from './components/componentsIndex';

export default () => {
  return (
    <BlueKit
      componentsIndex={componentsIndex}
      name="MyStyleGuide" // optional
    />
  );
}

By default BlueKit generates a set of component variations using random combination of props. In some cases it can be useful to enforce more precise declarations (e.g. using PropTypes.oneOf(...) method) and prevent unwanted behaviour. Yet if you desire to have more control on the final look of the documentation you can edit the component’s definition in the componentsIndex.js file:

MyComponent: {
  name: 'MyComponent',
  menu: 'MyComponent',
  file: './MyComponent/index.js',
  component: MyComponent,
  componentName: 'My Component',
  description: 'Sample component description',
  customProps: {},
  propsDefinition: {
    color: {
      type: {
        name: "string"
      },
      required: false,
      description: "",
      defaultValue: {
        value: "'#fff'",
        computed: false
      }
    }
  },
  simpleProps: {
    color: "#fff"
  },
  fullProps: {
    color: "#fff"
  }
}

PROS:

  • Hot module reload
  • TypeScript support - BlueKit uses react-docgen-typescript parser for .tsx files
  • Preview includes global components list and separate views in isolation
  • Useful UI features like background color invert or color picker
  • Very easy props manipulation (inputs types are generated according to propTypes)
  • By default creates a set of random variations of each component
  • The props that don’t affect the component’s look are automatically hidden

CONS:

  • Lack of support for variables in defaultProps
  • Styled and connected components are not supported yet

Catalog

Docs & demo: https://interactivethings.github.io/catalog/#/
GitHub: https://github.com/interactivethings/catalog/

Catalog style guide example

Catalog is the only tool on the list that wasn’t created primarily with React on mind, but is already a mature project with established community, and just recently added support for React components. That makes it to work effortlessly regardless the technology used, or the type of components and items we want to document, can it be standalone code blocks, color palettes, typography, static files, etc.

Documentation is generated by rendering the Catalog component supplied with a set of component pages definitions:

import React from 'react';
import ReactDOM from 'react-dom';
import { Catalog } from 'catalog';

import MyComponent from './MyComponent';

ReactDOM.render(
  <Catalog
    title='My Style Guide'
    pages={[
      {
        imports: { MyComponent },
        path: '/',                            // The path where the page can be accessed
        title: 'My Component',                // The page title
        src: require('./docs/MyComponent.md') // Path to the markdown definition
      },
      // Other pages ...
    ]}
  />,
  document.getElementById('app')
);

The component definitions are handled primarily as Markdown code blocks, also referred as specimen blocks, denoted with corresponding type, e.g. react, color-palette, image, download (see full list of supported types here).

```react
<MyComponent size=”large” />

Note: in case of React components without complex configuration you can reference them directly in the page object definition in the following way:

{
  path: '/',
  title: 'My Component',
  component: MyComponent
}

PROS:

  • Flexibility in documenting different types of UI elements
  • Specimens are easy to setup and configure
  • Support for styled components
  • Provides internal configureRoutes method which gives more flexibility when defining and combining routes, using them for server-side rendering, etc.

CONS:

  • Lack of support for hot module reload by default
  • Less out-of-the-box handling react components, requires more manual work

Other approaches

Apart of the tools listed above which are the most easy to configure and feature-rich, there are a couple of similar projects worth attention such as React Styleguide Generator, React Style Guide, Carte Blanche, Atellier and React Cosmos, the two latter with the powerful component playground features. There is also a Styleguidist plugin for a SourceJS style guide engine that allows an easy integration of React components on this popular platform. From a designer perspective the most worth mentioning is React Sketch.app library that allows you to write React components that render to Sketch documents.

If none of the existing solutions listed above matches your project’s expectations, why not to create your own tool? The easiest approach would be to define a higher-order component that renders given elements together with the representation of it’s raw markup. To implement more sophisticated features, such as automatic component detection and props analysis we could use react-docgen that parses not-transpiled source files, finds exported React components and generates documentation based on propTypes. As we saw in the previous examples Markdown is the most straightforward way to represent elements’ definitions, thus we could extract its code blocks using any markdown processor (e.g. Remark) and render them as an interactive playground with a code editor tool such as CodeMirror or ACE.

Conclusion

Style guide driven design and development seems to be extremely helpful for the maintenance of any modern frontend applications. It helps in establishing a shared vocabulary in the team, allows to find patterns in the UI and provides an useful platform to develop and test components in isolation.

From the tools highlighted in this article Storybook seems to be a step ahead of the others, primarily because of the strong community and the powerful Addons API, but we strongly recommend to test the other ones as they might be a better match depending on your project requirements. To help with the comparison we created this repository where you can see the most popular libraries in action.

Are you already using living style guides to document you React components? Do you suggest any other tools that are worth mentioning? Have you created your own library? Share your thoughts in the comments section!

Subscribe to our monthly newsletter!
join the discussion