API

Core Addon API

This is the core addon API. This is how to get the addon API:

  1. import { addons } from '@storybook/addons';

Have a look at the API methods for more details:

addons.getChannel()

Get an instance to the channel where you can communicate with the manager and the preview. You can find this in both the addon register code and in your addon’s wrapper component (where used inside a story).

It has a NodeJS EventEmitter compatible API. So, you can use it to emit events and listen for events.

addons.register()

This method allows you to register an addon and get the storybook API. You can do this only in the Manager App.See how we can use this:

  1. import { addons } from '@storybook/addons';
  2. // Register the addon with a unique name.
  3. addons.register('my-organisation/my-addon', api => {});

Now you’ll get an instance to our StorybookAPI. See the api docs for Storybook API regarding using that.

addons.add()

This method allows you to add a panel to Storybook. (Storybook’s Action Logger is a panel). You can do this only in the Manager App.See how you can use this method:

  1. import { addons, types } from '@storybook/addons';
  2. import { AddonPanel } from '@storybook/components';
  3. const MyPanel = () => <div>This is a panel.</div>;
  4. // give a unique name for the panel
  5. addons.add('my-organisation/my-addon/panel', {
  6. title: 'My Addon',
  7. type: types.PANEL,
  8. render: ({ active, key }) => (
  9. <AddonPanel active={active} key={key}>
  10. <MyPanel />
  11. </AddonPanel>
  12. ),
  13. });

The render function is called with active and key.

When the panel is in focus in the UI, the active will be true.

As you can see, you can set any React Component as the panel. Currently, it’s just a text. But you can do anything you want. You should specify the panel title. It could be a plain text.

makeDecorator API

The makeDecorator API can be used to create decorators in the style of the official addons easily. Use it like so:

  1. import { makeDecorator } from '@storybook/addons';
  2. export makeDecorator({
  3. name: 'withSomething',
  4. parameterName: 'something',
  5. wrapper: (storyFn, context, { parameters }) => {
  6. // Do something with `parameters`, which are set via { something: ... }
  7. // Note you may alter the story output if you like, although generally that's
  8. // not advised
  9. return storyFn(context);
  10. }
  11. })

The options to makeDecorator are:

  • name: The name of the export (e.g. withFoo)
  • parameterName: The name of the parameter your addon uses. This should be unique.
  • skipIfNoParametersOrOptions: Don’t run your decorator if the user hasn’t set options (via .addDecorator(withFoo(options)))) or parameters (.add('story', () => <Story/>, { foo: 'param' }), or .addParameters({ foo: 'param' })).
  • allowDeprecatedUsage: support the deprecated “wrapper” usage (.add('story', () => withFoo(options)(() => <Story/>))).
  • wrapper: your decorator function. Takes the storyFn, context, and both the options and parameters (as defined in skipIfNoParametersOrOptions above).Note if the parameters to a story include { foo: { disable: true } } (where foo is the parameterName of your addon), your decorator will not be called.

Storybook hooks

Writing addons can be simplified a lot by using these Storybook hooks:

useStorybookState

  1. export const Panel = () => {
  2. const state = useStorybookState();
  3. return <div>do something with storybook's state</div>;
  4. }

Allows full access to the entire storybook state.Your component will re-render whenever the storybook state changes.

If you use this, remember your component wil be re-rendered a lot, and you may need to optimize for that using React.memo or useMemo or PureComponent.

useStorybookApi

  1. export const Panel = () => {
  2. const state = useStorybookApi();
  3. return <div>do something with storybook's api</div>;
  4. }

Allows full access to the storybook API.

Detail on the storybook api are further down.

useChannel

  1. import { STORY_CHANGED } from '@storybook/core-events';
  2. export const Panel = () => {
  3. const emit = useChannel({
  4. STORY_CHANGED: (...args) => console.log(...args),
  5. });
  6. return (
  7. <button onClick={() => emit('my-event-type', { some: 'data' })}>
  8. clicking this will emit an event
  9. </button>
  10. );
  11. }

Allows for both setting subscriptions to events and getting the emitter for emitting custom event unto the channel.

The messages can be listened for on both the iframe and the manager side.

useAddonState

  1. export const Panel = () => {
  2. const [state, setState] = useAddonState('my/addon-id', 'initial state');
  3. return (
  4. <button onClick={() => setState('a new value')}>
  5. the state = "{state}"
  6. </button>
  7. );
  8. }
  9. export const Tool = () => {
  10. const [state, setState] = useAddonState('my/addon-id', 'initial state');
  11. return (
  12. <button onClick={() => setState('a new value')}>
  13. the state = "{state}"
  14. </button>
  15. );
  16. }

Extremely useful for addons that need to persist some state.

Storybook may unmount your addon component, and so keeping local state, might not work really well.

Also some addons consist of multiple parts, some part being in a panel, some in the toolbar etc.

With this hook they can all get access to the same bit of state which is persisted even if the components are unmounted.

useParameter

  1. export const Panel = () => {
  2. const value = useParameter('parameter-key', 'default value');
  3. return (
  4. <div>
  5. for the currently selected story, the parameter for "parameter-key" is:
  6. {value}
  7. </div>
  8. );
  9. }

This hook gets you the current story’s parameter super easy.

If the parameter isn’t set, the default value (second argument) is returned instead.


Storybook API

Storybook API allows you to access different functionalities of Storybook UI. You can move an instance to the Storybook API when you register an addon.

Let’s have a look at API methods.

api.selectStory()

With this method, you can select a story via an API. This method accepts two parameters.

  • story kind name
  • story name (optional)Let’s say you’ve got a story like this:
  1. import { storiesOf } from '@storybook/react';
  2. storiesOf('heading', module).add('with text', () => <h1>Hello world</h1>);

This is how you can select the above story:

  1. addons.register('my-organisation/my-addon', api => {
  2. api.selectStory('heading', 'with text');
  3. });

api.selectInCurrentKind()

Same as selectStory, but accepts a story inside current kind as the only parameter:

  1. addons.register('my-organisation/my-addon', api => {
  2. api.selectInCurrentKind('with text');
  3. });

api.setQueryParams()

This method allows you to set query string parameters. You can use that as temporary storage for addons. Here’s how you set query params.

  1. addons.register('my-organisation/my-addon', api => {
  2. api.setQueryParams({
  3. abc: 'this is abc',
  4. bbc: 'this is bbc',
  5. });
  6. });

If you need to remove a query param, use null for that. For an example, let’s say we need to remove bbc query param. This is how we do it:

  1. addons.register('my-organisation/my-addon', api => {
  2. api.setQueryParams({
  3. bbc: null,
  4. });
  5. });

api.getQueryParam()

This method allows you to get a query param set by above API setQueryParams. For example, let’s say we need to get the bbc query param. Then this how we do it:

  1. addons.register('my-organisation/my-addon', api => {
  2. api.getQueryParam('bbc');
  3. });

api.getUrlState(overrideParams)

This method allows you to get application url state with some changed params. For example, if you want to get a link to a particular story:

  1. addons.register('my-organisation/my-addon', api => {
  2. const href = api.getUrlState({
  3. selectedKind: 'kind',
  4. selectedStory: 'story',
  5. }).url;
  6. });

deprecated APIs

api.onStory(fn)

This method allows you to register a handler function which will be called whenever the user navigates between stories.

  1. addons.register('my-organisation/my-addon', api => {
  2. api.onStory((kind, story) => console.log(kind, story));
  3. });