4

When we load a storybook addon we can pass some options:

// .storybook/main.js

module.exports = {
  addons: [
    'a-storybook-addon-without-options',
    {
      name: 'a-storybook-addon-with-options',
      options: {
        mainColor: 'hotpink',
      },
    },
  ],
};

To write my addon I use the addon API:

// /a-storybook-addon-with-options/src/register.js

import React from 'react';
import { addons, types } from '@storybook/addons';
import MyComponent from './myComponent.js';

const ADDON_ID = 'myaddon';
const PANEL_ID = `${ADDON_ID}/panel`;

addons.register(ADDON_ID, (api) => {
  addons.add(PANEL_ID, {
    type: types.PANEL,
    title: 'My Addon',
    render: MyComponent,
  });
});

I don't know how to get the developer options from the addon code. Is there an official way? I didn't get a clear help from the documentation.

tzi
  • 8,719
  • 2
  • 25
  • 45

2 Answers2

0

I think here you should use a parameter instead of this option in the config.

This kind of config (the options field) is more for presets that alter webpack or babel config.

If you add a parameter in the preview with the key that you specify in the register file then you can easily access that parameter in the addon code.

in preview.js

export const parameters = {
  myAddon: {
    mainColor: 'red'
  },
};

in the addon code

import { useParameter } from '@storybook/api';

const PARAM_KEY = 'myAddon';

const MyPanel = () => {
  const value = useParameter(PARAM_KEY, null);
  const mainColor = value ? value.mainColor : 'No mainColor defined';
  return <div>{mainColor}</div>;
};
Danny
  • 895
  • 11
  • 21
  • If a developer use my addon, would he be able to override this parameter? If yes, how? – tzi Feb 24 '22 at 21:31
  • Parameters are defined by the user/developer so they can set it to whatever they want either in the story parameters or in the preview.js – Danny Feb 25 '22 at 13:57
  • You could set some default by setting a value when they don't set any value on the parameter like: `const mainColor = value ? value.mainColor : 'red';` – Danny Feb 25 '22 at 14:00
0

You could set some default by setting a value when they don't set any value on the parameter like:

const mainColor = value ? value.mainColor : 'red'; 
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77