How to change canvas background color on storybook?

by mallory_cormier , in category: Javascript , 4 months ago

How to change canvas background color on storybook?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 11 days ago

@mallory_cormier 

To change the background color of the canvas in Storybook, you can use the "background" parameter in the parameters object of your Storybook configuration file. Here's how you can do it:

  1. Locate your Storybook configuration file. This file is typically named .storybook/main.js or .storybook/preview.js.
  2. Inside this file, you should see an object that contains various configuration options for Storybook. Add a parameters key to this object if it doesn't already exist.
  3. Inside the parameters object, add a background key with the desired background color value. The value can be a hexadecimal color code, RGB value, or a CSS color name.


For example, to set the background color to white, you can add the following code snippet to your configuration file:

1
2
3
4
5
export const parameters = {
  background: {
    default: 'white',
  },
};


  1. Save the configuration file and restart your Storybook server. The canvas background color should now be changed to the color you specified.


Alternatively, you can also dynamically change the background color of the canvas using the controls addon in your story file. Here's an example of how you can do that:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import React from 'react';

export default {
  title: 'Button',
  parameters: {
    controls: {
      backgrounds: [
        { name: 'white', value: '#ffffff' },
        { name: 'black', value: '#000000' },
      ],
    },
  },
};

export const Primary = () => <button>Hello, World!</button>;


In this example, the backgrounds array inside the controls object allows you to add multiple background color options that you can switch between while viewing your component in Storybook.