javascriptreactjsstorybook

Rendering multiple variants with Storybook


I am building my storybook documentation for a library I built with React and I am not finding a easy way to render multiple variants in the same page.

So, what I have so far is something like this

const Template = (args, { argTypes }) => <Title {...args} />

export const Primary = Template.bind({});
export const Success = Template.bind({});
export const Warning = Template.bind({});
export const Inverse = Template.bind({});
export const Default = Template.bind({});
export const Info = Template.bind({});
export const Danger = Template.bind({});
export const Disabled = Template.bind({});

Primary.args = {
  children: 'Primary',
  level: 3, // <- this can go from 1 to 5,
  as: 'h1', 
  variant: 'primary',
}

Success.args = {
  children: 'Success',
  level: 3, // <- this can go from 1 to 5,
  as: 'h1',
  variant: 'success',
}

etc...

This generates this:

enter image description here

and I am trying to achieve something like this when I render each variant:

enter image description here

How can I do something like that with Storybook?


Solution

  • You can render multiple instance of Component inside a Story by using decorators

    Sample code (should be similar for your code):

    export const Primary = Template.bind({});
    Primary.args = {
      primary: true,
      label: 'Button',
    };
    
    Primary.decorators = [
      () => {
        return (
          <>
            <Button {...Primary.args as ButtonProps} level={1} />
            <Button {...Primary.args as ButtonProps} level={2} />
            <Button {...Primary.args as ButtonProps} level={3} />
          </>
        );
      },
    ];
    

    Output:

    enter image description here

    More info, there are 3 level of decorators, it worth a read:

    1. Story level
    2. Component level
    3. Global level