Creating a custom color control in Storybook

Recently, I’ve been working with Storybook to create a component library for a website redesign project. When we preview components in Storybook, Storybook’s controls give us an interactive UI that lets us modify a component’s props on the fly.

We wanted to set up a control that allows us to change the color of elements in our component. Specifically, we had a scrolling carousel of logos (SVG files) and we wanted our Storybook control to change the color of those logos using colors from our Styled Components theme.

After a look at Storybook’s docs, we discovered that it’s pretty easy to add a color control that displays a color picker. We can also pass an array of strings to the presetColors prop of the color control that adds swatches to the color picker. However, we want to see the names of the colors we’re selecting, and the color picker UI doesn’t have enough space to display swatches for all of the colors in our theme.

Storybook's color picker and swatches

The Storybook docs include a section about dealing with complex values, which provides some guidance on creating a control that uses a select input with options mapped from an object’s keys and values. Let’s set up a Storybook story and control to do this!

In our theme, we use a colors object with properties that include the name of a color and its corresponding HEX value:

const colors = {
  blue: '#2949E5',
  green: '#268713',
  orange: '#D1451A',
  ...
};

Let’s take a look at what our story looks like:

const Story = {
  title: 'Components/Logos',
  component: Logos, // A component that renders an infinite scrolling carousel of logos
  argTypes: {
    color: {
      options: Object.keys(colors),
      mapping: colors,
      control: { type: 'select' }, // The input type we want to use for our control
      description: 'Color of logos to be displayed', // A descripton of what this control does
    },
  },
} satisfies Meta<typeof Logos>; // The Meta type pulls props from the component to provide metadata to Storybook

Opening up the argTypes object is how we can specify what we want a control to be. We’re describing the color control here, which is a prop of the Logos component.

First, we tell Storybook that this control is a select input. We pass the keys of our theme’s colors object into the options property to be used as titles of options for the select input rendered by the control. To provide values for these options, we pass the entire colors object into the mapping field. We also add a description describing the purpose of the color prop in the Logos component.

Custom color picker using a select input with options mapped from our theme's colors

I hope this example is useful if you need to create a custom colors control in Storybook!