Michael Shilman a6d81914c2 v6.0.0-beta.9
2020-05-21 07:17:20 +08:00
..
2020-05-21 07:17:20 +08:00
2020-05-12 16:37:51 +02:00
2018-05-03 02:03:30 +03:00
2019-03-15 19:57:56 +01:00

Storybook Addon Backgrounds

Storybook Background Addon can be used to change background colors inside the preview in Storybook.

Framework Support

React Storybook Screenshot

Installation

yarn add @storybook/addon-backgrounds --dev

Configuration

If it doesn't exist yet, create a file called main.js in your storybook config.

Add the following content to it:

module.exports = {
  addons: ['@storybook/addon-backgrounds']
}

Usage

Backgrounds requires two parameters:

  • default - matches the name of the value which will be selected by default.
  • values - an array of elements containing name and value (with a valid css color e.g. HEX, RGBA, etc.)

Write your stories like this:

import React from 'react';

/*
 * Button.stories.js
 * Applies backgrounds to the Stories 
 */
export default {
  title: 'Button',
  parameters: {
    backgrounds: {
      default: 'twitter',
      values: [
        { name: 'twitter', value: '#00aced' },
        { name: 'facebook', value: '#3b5998' },
      ],
    },
  },
};

export const defaultView = () => (
  <button>Click me</button>
);

You can add the backgrounds to all stories by using parameters in .storybook/preview.js:

export const parameters = {
  backgrounds: {
    default: 'twitter',
    values: [
      { name: 'twitter', value: '#00aced' },
      { name: 'facebook', value: '#3b5998' },
    ],
  },
};

If you want to override backgrounds for a single story or group of stories, pass the backgrounds parameter:

import React from 'react';

export default {
  title: 'Button',
}

export const defaultView = () => (
  <button>Click me</button>
);

defaultView.story = {
  parameters: {
    backgrounds: {
      default: 'red',
      values: [
        { name: 'red', value: 'rgba(255, 0, 0)' },
      ],
    },
  }
};

Once you have defined backgrounds for your stories (as can be seen in the examples above), you can set a default background per story by passing the default property using a name from the available backgrounds:

import React from 'react';

/*
 * Button.stories.js
 * Applies default background to the Stories 
 */
export default {
  title: 'Button',
  parameters: {
    backgrounds: { default: 'twitter' },
  },
}

export const twitterColorSelected = () => (
  <button>Click me</button>
);

If you don't want to use backgrounds for a story, you can set the backgrounds parameter to { disable: true } to skip the addon:

import React from 'react';

/*
 * Button.stories.js
 * Disables backgrounds for one Story 
 */
export default {
  title: 'Button',
}

export const disabledBackgrounds = () => (
  <button>Click me</button>
);

disabledBackgrounds.story = {
  parameters: {
    backgrounds: { disable: true },
  },
};