React Styleguidist

Cookbook

How to use refs in examples?

Use ref prop as a function and assign a reference to a local variable:

initialState = { value: '' };
let textarea;
<div>
  <Button onClick={() => textarea.insertAtCursor('Pizza')}>Insert</Button>
  <Textarea value={state.value} onChange={e => setState({ value: e.target.value })} ref={ref => textarea = ref} />
</div>

How to exclude some components from style guide?

Styleguidist will ignore tests (__tests__ folder and file names containing .test.js or .spec.js) by default.

Use ignore option to customize this behavior:

module.exports = {
  ignore: [
    '**/*.spec.js',
    '**/components/Button.js'
  ]
};

You should pass glob patterns, for example, use **/components/Button.js instead of components/Button.js.

How to hide some components in style guide but make them available in examples?

Enable skipComponentsWithoutExample option and do not add example file (Readme.md by default) to components you want to ignore.

Require these components in your examples:

const Button = require('../common/Button');
<Button>Push Me Tender</Button>

Or, if you want to make these components available for all examples:

// styleguide.config.js
module.exports = {
  require: [
    path.resolve(__dirname, 'styleguide/setup.js')
  ]
}

// styleguide/setup.js
import Button from './src/components/common/Button';
global.Button = Button;

The Button component will be available in every example without a need to require it.

How to add custom JavaScript and CSS or polyfills?

In your style guide config:

const path = require('path');
module.exports = {
  require: [
    'babel-polyfill',
    path.join(__dirname, 'path/to/script.js'),
    path.join(__dirname, 'path/to/styles.css'),
  ]
};

How to use React Styleguidist with Preact?

You need to alias react and react-dom to preact-compat:

module.exports = {
  webpackConfig: {
    resolve: {
      alias: {
        'react': 'preact-compat',
        'react-dom': 'preact-compat',
      }
    }
  }
};

See the Preact example style guide.

How to change styles of a style guide?

There are two config options to change your style guide UI: theme and styles.

Use theme to change fonts, colors, etc.

Use styles to tweak the style of any particular Styleguidist component.

As an example:

module.exports = {
  theme: {
    color: {
      link: 'firebrick',
      linkHover: 'salmon',
    },
    fontFamily: {
      base: '"Comic Sans MS", "Comic Sans", cursive'
    }
  },
  styles: {
    Logo: {
      logo: {
        animation: 'blink ease-in-out 300ms infinite'
      },
      '@keyframes blink': {
        to: { opacity: 0 }
      }
    }
  }
};

See available theme variables.

Styles use JSS with these plugins: jss-isolate, jss-nested, jss-camel-case, jss-default-unit, jss-compose.

Use React Developer Tools to find component and style names. For example a component <LogoRenderer><h1 className="logo-524678444">… corresponds to an example above.

How to change the layout of a style guide?

You can replace any Styleguidist React component. But in most of the cases you’ll want to replace *Renderer components — all HTML is rendered by these components. For example ReactComponentRenderer, ComponentsListRenderer, PropsRenderer, etc. — check the source to see what components are available.

There’s also a special wrapper component —Wrapper — that wraps every example component. By default it just renders children as is but you can use it to provide a custom logic.

For example you can replace the Wrapper component to wrap any example in the React Intl’s provider component. You can’t wrap the whole style guide because every example is compiled separately in a browser.

// styleguide.config.js
const path = require('path');
module.exports = {
  styleguideComponents: {
    Wrapper: path.join(__dirname, 'lib/styleguide/Wrapper')
  }
};
// lib/styleguide/Wrapper.js
import React, { Component } from 'react';
import { IntlProvider } from 'react-intl';
export default class Wrapper extends Component {
  render() {
    return (
      <IntlProvider locale="en">
        {this.props.children}
      </IntlProvider>
    );
  }
}

You can replace the StyleGuideRenderer component like this:

// styleguide.config.js
const path = require('path');
module.exports = {
  styleguideComponents: {
    StyleGuideRenderer: path.join(__dirname, 'lib/styleguide/StyleGuideRenderer')
  }
};
// lib/styleguide/StyleGuideRenderer.js
import React from 'react';
const StyleGuideRenderer = ({ title, homepageUrl, components, toc, hasSidebar }) => (
  <div className="root">
    <h1>{title}</h1>
    <main className="wrapper">
      <div className="content">
        {components}
        <footer className="footer">
          <Markdown text={`Generated with [React Styleguidist](${homepageUrl})`} />
        </footer>
      </div>
      {hasSidebar &&
        <div className="sidebar">
          {toc}
        </div>
      }
    </main>
  </div>
);

We have an example style guide with custom components.

How to change style guide dev server logs output?

You can modify webpack dev server logs format changing stats option of webpack config:

module.exports = {
  webpackConfig(env) {
    if (env === 'development') {
      return {
        stats: {
          chunks: false,
          chunkModules: false,
          chunkOrigins: false,
        },
      };
    }
    return {};
  }
};

How to debug my components and examples?

  1. Open your browser’s developer tools
  2. Write debugger; statement wherever you want: in a component source, a Markdown example or even in an editor in a browser.

How to debug the exceptions thrown from my components?

  1. Put debugger; statement at the beginning of your code.
  2. Press the Debugger button in your browser’s developer tools.
  3. Press the Continue button and the debugger will stop execution at the next exception.

How to use React's production or development build?

In some cases, you might need to use React's development build instead of the default production one. For example, this might be needed if you use React Native and make references to a React Native component's propTypes in your code. As React removes all propTypes in its production build, your code will fail. By default, React Styleguidist uses the development build for the dev server, and the production one for static builds.

import React from 'react';
import { TextInput } from 'react-native';

const CustomInput = ({value}) => <TextInput value={value} />;

CustomInput.propTypes = {
  // will fail in a static build
  value: TextInput.value.isRequired,
};

If you use code similar to this, you might encounter errors such as Cannot read property 'isRequired' of undefined.

To avoid this, you need to tell React Styleguidist to use React's development build. To do this, simply set the NODE_ENV variable to development in your npm script.

{
  "scripts": {
    "build": "cross-env NODE_ENV=development react-styleguidist build"
  }
}

The script above uses cross-env to make sure the environment variable is properly set on all platforms. Run npm i -D cross-env to add it.

Why does the style guide list one of my prop types as unknown?

This occurs when you are assigning props via getDefaultProps that are not listed within the components propTypes.

For example, the color prop here is assigned via getDefaultProps but missing from the propTypes, therefore the style guide is unable to display the correct prop type.

Button.propTypes = {
  children: PropTypes.string.isRequired,
  size: PropTypes.oneOf(['small', 'normal', 'large'])
};

Button.defaultProps = {
  color: '#333',
  size: 'normal'
};

Why object references don’t work in example component state?

Object references will not work as expected in examples state due to how the examples code is evaluated:

const items = [
  {id: 0},
  {id: 1}
];

initialState = {
  activeItemByReference: items[0],
  activeItemByPrimitive: items[0].id
};

<div>
  {/* Will render "not active" because of object reference: */}
  {state.activeItemByReference === items[0] ? 'active' : 'not active'}
  {/* But this will render "active" as expected: */}
  {state.activeItemByPrimitive === items[0].id ? 'active' : 'not active'}
</div>

How to use Vagrant with Styleguidist?

First read Vagrant guide from the webpack documentation. Then enable polling in your webpack config:

devServer: {
  watchOptions: {
    poll: true
  }
}

How to reuse project’s webpack config?

See in configuring webpack.

How to use React Styleguidist with Redux, Relay or Styled Components?

See working with third-party libraries.

What’s the difference between Styleguidist and Storybook

Both tools are good and mature, they have many similarities but also some distinctions that may make you choose one or the other. For me the biggest distinction is how you describe component variations.

With Storybook you write stories in JavaScript files:

import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import Button from '../components/Button';

storiesOf('Button', module)
  .add('default', () => (
    <Button onClick={action('clicked')}>Push Me</Button>
  ))
  .add('large size', () => (
    <Button size="large">Push Me</Button>
  ));

Storybook screenshot

And with Styleguidist you write examples in Markdown files:

React button component example:

```js
<Button onClick={() => console.log('clicked')>Push Me</Button>
```

Large size:

```js
<Button size="large">Push Me</Button>
```

Styleguidist screenshot

Another important distinction is that Storybook shows only one variation of one component at a time but Styleguidist can show all variations of all components, all variations of a single component or one variation. It’s easier to create a style guide with Styleguidist but Storybook has more tools to develop components (though we’re working on that too).

Feature Storybook Styleguidist
Component examples JavaScript Markdown
Props docs Yes Yes
Public methods docs No Yes
Style guide¹ No Yes
Customizable design No Yes
Extra documentation² No Yes
Plugins Many In development
React Yes Yes
Preact Yes Yes
React Native Yes react-native-web
Vue Yes Fork

¹ All components on a single page.
² Include non-component documentation.

Are there any other projects like this?

  • Atellier, a React components emulator.
  • Carte Blanche, an isolated development space with integrated fuzz testing for your components.
  • Catalog, create living style guides using Markdown or React.
  • Cosmos, a tool for designing truly encapsulated React components.
  • React BlueKit, render React components with editable source and live preview.
  • React Cards, devcards for React.
  • React Styleguide Generator, a React style guide generator.
  • React Storybook, isolate your React UI Component development from the main app.
  • React-demo, a component for creating demos of other components with props editor.
  • SourceJS, a platform to unify all your frontend documentation. It has a Styleguidist plugin.