Storybook default selection control value
Asked Answered
B

3

8

I'm using Storybook with React, and trying to add storybook select control with default value, but with no success. There's nothing about that in documentation. enter image description here

enter image description here

I need one of the options above to be selected by default.

    argTypes: {
        iconSrc: {
            options: Object.keys(iconTypes),
            mapping: iconTypes,
            control: {
                sort: 'requiredFirst',
                type: 'select',
                labels: {
                    BlueStep: 'Blue Step',
                    Step: 'Step',
                    Globe: 'Globe',
                },
            },
        },
    }

Bly answered 19/4, 2022 at 9:35 Comment(0)
V
7

You have to add the table key

your storybook will look like this:

 argTypes: {
        iconSrc: {
            options: Object.keys(iconTypes),
            mapping: iconTypes,
            control: {
                sort: 'requiredFirst',
                type: 'select',
                labels: {
                    BlueStep: 'Blue Step',
                    Step: 'Step',
                    Globe: 'Globe',
                },
            },
            table: {
              type: { summary: 'select' },
              defaultValue: { summary: 'Step' },
            },
        },
    }
Volgograd answered 20/7, 2022 at 19:14 Comment(1)
This is the way.Khartoum
A
4

You'll need pass args to your story template like:

const Template = (args) => <YourComponent {...props} />;

export const Default = Template.bind({});

Default.args = {
  iconSrc: 'icon-source-string',
};

Example from storybook official doc: https://storybook.js.org/docs/react/essentials/controls

Anjanette answered 19/4, 2022 at 12:6 Comment(3)
What if we already define the default value in our React component? How do we get storybook to get those values?Vince
If you want to use default values from React component, either don't pass that prop in args or pass value as undefinedAnjanette
If we pass nothing or undefined, the control will not show the selected default valueVince
O
2

The most upvoted answer at time of writing refers to the table key, which is used for specifying how an arg is documented.

However the question is asking how to set a default that will be the initially selected option on the <select/> element rendered when using the select control. In the rendered HTML this would be done by setting the selected boolean on the <option/> intended as default.

It appears that Storybook does not expose a way to accomplish this, and that this is by design (for better or worse). Instead an optional control value is initialized to undefined. defaultValue has been deprecated.

Only answered 18/11, 2023 at 20:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.