Search code examples
reactjsstorybook

React Storybook: Trying to set specific actions to different Templates


So, in the docs, it shows how to handle all onClick events for the default button. But, I want to return a different action name for each button.

But, it doesn't show how to do this.

It used to involve importing action from @storybook/addon-actions

But, it's changed since then. If I click on the 'Sign Up' button, I'd like to see the signUp action triggered. Hopefully that makes sense.

Here is my current code:

export default {
  title: 'Button',
  component: Button,
  argTypes: {
    onClick: {
      action: 'clicked'
    }
  }
} as ComponentMeta<typeof Button>;

const Template: ComponentStory<typeof Button> = (args) => <Button {...args} />;

export const Default = Template.bind({});
Default.args = {
  children: 'Primary',
  variant: 'primary',
}

export const Secondary = Template.bind({});
Secondary.args = {
  children: 'Secondary',
  variant: 'secondary',
  argTypes: {
    onClick: {
      action: 'Secondary clicked'
    }
  }
}

Solution

  • You can override Template.argTypes attribute on the Secondary component and achieve the same behavior.

    export const Secondary = Template.bind({});
    Secondary.args = {
      children: 'Secondary',
      variant: 'secondary',
    }
    
    Secondary.argTypes = {
      onClick: {
        action: 'Secondary clicked'
      }
    }