Search code examples
javascriptreactjsstorybook

How do I reuse knobs in Storybook's Component Story Format (CSF)?


I've a simple Button component with multiple stories. All these stories need the same knobs configuration.

This approach works:

export const Default = () => <Button size={select('size', ['x-large', 'normal', 'x-small'], 'x-small')}>Button</Button>;
export const Disabled = () => <Button disabled size={select('size', ['x-large', 'normal', 'x-small'], 'x-small')}>Button</Button>;
export const Outline = () => <Button outline size={select('size', ['x-large','normal', 'x-small'], 'x-small')}>Button</Button>;

However, I don't want to repeat the select statement over and over. I tried spreading, like so:

const knobs = {
  size: select('size', ['x-large', 'normal', 'x-small'], 'x-small')
};
​
export const Default = () => <Button {...knobs}>Button</Button>;
export const Disabled = () => <Button disabled {...knobs}>Button</Button>;
export const Outline = () => <Button outline {...knobs}>Button</Button>;

But doesn't work: the knobs show in the UI, but when I update the dropdown, the new value isn't passed to the knob.

What am I doing wrong here?


Solution

  • Apparently this works when you spread the props as a function. This is how I eventually got things working:

    const knobs = () => ({
      size: select('size', ['x-large', 'normal', 'x-small'], 'x-small')
    });
    ​
    export const Default = () => <Button {...knobs()}>Button</Button>;
    export const Disabled = () => <Button disabled {...knobs()}>Button</Button>;
    export const Outline = () => <Button outline {...knobs()}>Button</Button>;