Skip to content

Latest commit

 

History

History
353 lines (282 loc) · 11 KB

File metadata and controls

353 lines (282 loc) · 11 KB

Cookbook

How to reuse project’s webpack config?

See in configuring webpack.

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',
    'src/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>

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 connect Redux store?

To use Redux store with one component require it from your example:

const { Provider } = require('react-redux');
const configureStore = require('../utils/configureStore').default;
const initialState = {
  app: {
    name: 'Pizza Delivery'
  }
};
const store = configureStore({ initialState });
<Provider store={store}>
  <App greeting="Choose your pizza!"/>
</Provider>

To use Redux store in every component redefine the Wrapper component:

// styleguide.config.js
const path = require('path');
module.exports = {
  webpackConfig: {
    resolve: {
      alias: {
        'rsg-components/Wrapper': path.join(__dirname, 'lib/styleguide/Wrapper')
      }
    }
  }
};

// lib/styleguide/Wrapper.js
import React, { Component } from 'react';
const { Provider } = require('react-redux');
const configureStore = require('../utils/configureStore').default;
const initialState = {
  app: {
    name: 'Pizza Delivery'
  }
};
const store = configureStore({ initialState });
export default class Wrapper extends Component {
  render() {
    return (
      <Provider store={store}>
        {this.props.children}
      </Provider>
    );
  }
}

How to use React Styleguidist with styled-components?

The recommended way of using styled-components is like this:

import React, { Component } from 'react';
import styled from 'styled-components';

const SalmonButton = styled.button`
  background-color: salmon;
  border: 1px solid indianred;
  color: snow;
`;

class Button extends Component {
  render() {
    return <SalmonButton>{this.props.children}</SalmonButton>;
  }
}

export default Button;

You may need an appropriate webpack loader to handle these files.

Note: to change style guide styles use theme and styles options (see the next question).

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.

Warning: Preact support is experimental and far from perfect. Feel free to send a pull request to imporove it.

How to change styles of a style guide?

Use config option theme to change fonts, colors, etc. and option styles to tweak style of particular Styleguidist’s components:

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

Note: See available theme variables.

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

Note: 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 will 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 = {
  webpackConfig: {
    resolve: {
      alias: {
        'rsg-components/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 = {
  webpackConfig: {
    resolve: {
      alias: {
        'rsg-components/StyleGuide/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.

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>

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.