3.6 KiB
Storybook Addon Actions
Storybook Addon Actions can be used to display data received by event handlers in Storybook.
Getting Started
Install:
npm i -D @storybook/addon-actions
Then, add following content to .storybook/addons.js
import '@storybook/addon-actions/register';
Import the action
function and use it to create actions handlers. When creating action handlers, provide a name to make it easier to identify.
Note: Make sure NOT to use reserved words as function names. issues#29
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import Button from './button';
storiesOf('Button', module).add('default view', () => (
<Button onClick={action('button-click')}>Hello World!</Button>
));
Multiple actions
If your story requires multiple actions, it may be convenient to use actions
to create many at once:
import { storiesOf } from '@storybook/react';
import { actions } from '@storybook/addon-actions';
import Button from './button';
// This will lead to { onClick: action('onClick'), ... }
const eventsFromNames = actions('onClick', 'onDoubleClick');
// This will lead to { onClick: action('clicked'), ... }
const eventsFromObject = actions({ onClick: 'clicked', onDoubleClick: 'double clicked' });
storiesOf('Button', module)
.add('default view', () => <Button {...eventsFromNames}>Hello World!</Button>)
.add('default view, different actions', () => (
<Button {...eventsFromObject}>Hello World!</Button>
));
Action Decorators
If you wish to process action data before sending them over to the logger, you can do it with action decorators.
decorate
takes an array of decorator functions. Each decorator function is passed an array of arguments, and should return a new arguments array to use. decorate
returns a object with two functions: action
and actions
, that act like the above, except they log the modified arguments instead of the original arguments.
import { decorate } from '@storybook/addon-actions';
import Button from './button';
const firstArg = decorate([args => args.slice(0, 1)]);
storiesOf('Button', module).add('default view', () => (
<Button onClick={firstArg.action('button-click')}>Hello World!</Button>
));