Uri Klar
Uri Klar

Reputation: 3988

Storybook 6 decorator pass props to story not working

I'm using @storybook/react v6.1.21. I want to have the option to pass state to my stories using state and setState props.

This is how I defined my decorator:

//preview.js
export const decorators = [
    Story => {
        const [state, setState] = useState();
        return <Story state={state} setState={setState} />;
    }
];

// mycomponent.stories.tsx

export const TwoButtons = ({ state, setState }) => (
    <ButtonGroup
        buttons={[
            { label: 'One',value: 'one'},
            { label: 'Two', value: 'two' }
        ]}
        selectedButton={state}
        onClick={val => setState(val)}
    />
);


But for some reason state and setState are undefined in the story. I had a similar setup working in Storybook v5.
Any idea what i'm missing?

Upvotes: 10

Views: 10861

Answers (1)

Phunkren
Phunkren

Reputation: 208

From the docs:

parameters.passArgsFirst: In Storybook 6+, we pass the args as the first argument to the story function. The second argument is the “context” which contains things like the story parameters etc.

You should be able to access state and setState by making a small adjustment to the story function signature:

//preview.js
export const decorators = [
    Story => {
        const [state, setState] = useState();
        return <Story state={state} setState={setState} />;
    }
];

// mycomponent.stories.tsx

export const TwoButtons = (args, context) => {
  const { state, setState } = context;

  return (
    <ButtonGroup
        buttons={[
            { label: 'One',value: 'one'},
            { label: 'Two', value: 'two' }
        ]}
        selectedButton={state}
        onClick={val => setState(val)}
    />
  );
}

Upvotes: 16

Related Questions