I have a component that has event emitters, and I need to provide a function to it for the component to function correctly.
Used as so:
<my-component (onClick)="myFunction()"></my-component>
So I'm trying this in Storybook, but I can't figure out how to define myFunction() in storybook.
Even when I create myFunction as an arg, I get
ERROR TypeError: ctx.myFunction is not a function
at StorybookWrapperComponent_Template_my_component_onClick_0_listener (template.html)
So how do I properly define this function. I don't see anything in Storybook's docs mentioning it, but I can't be the only person that needs this...
export default {
title: 'My Great Component',
component: MyComponent
} as Meta<MyComponent>;
const Template: Story<any> = (args) => ({
props: args,
template: `<my-component (onClick)="myFunction()"></my-component>`
});
export const Primary = Template.bind({});
Primary.args = {
myFunction: () => { alert('clicked'); }
}
I've also tried this, thinking that maybe hard coding my function as part of this, it would work, but nope...
export const Primary = Template.bind({myFunction: () => { alert('clicked');});
I'm thinking I might need a wrapper component, but doing that just to make storybook work feels excessive.
There is a more correct and dynamic solution: you must define the type of myFunction (as 'function') in argTypes, parameter of Meta.
This way you can configure a specific value for myFunction in every story. You don't have to specify the template if the arg is a component's input and has the same name.
Here is your example in CSF 3:
type MyComponentArgs = MyComponent & { myFunction: () => void };
const meta: Meta<MyComponentArgs> = {
title: 'My Great Component',
component: MyComponent,
argTypes: {
myFunction: { type: 'function', control: false },
},
};
export default meta;
type Story = StoryObj<MyComponentArgs>;
export const Primary: Story = {
render: (args) => ({
props: args,
template: `<my-component (onClick)="myFunction()"></my-component>`
}),
args: {
myFunction: () => { alert('clicked'); }
}
}
Note: I don't know why but control: false is mandatory, at least today with storybook v8.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With