ciaoben
ciaoben

Reputation: 3368

How to properly use external state in react/storybook

I am using the great storybook/react, but I have encountered a problem.

I have a lot of components that rely on props (are stateless), so in my real-world app I have containers components that keep state.

For example, I have a <Toggle />, as you can see here that get value from its parent and calls the onChange from its props to change it. I want to have this behavior in my storybook, but don't how to do it:

storiesOf('Toggle', module).add('', () => (
  <Toggle name="toggle" checked={/*  what here ? */} onChange={/* what here ? */} />
))

Upvotes: 3

Views: 2661

Answers (1)

Sambego
Sambego

Reputation: 46

You could use one of the storyebook state addons, like this one I published some time ago https://www.npmjs.com/package/@sambego/storybook-state

Your code might look like the following, where the checked property will be passed automatically from the store, and the onChange method will update the store.

const store = new Store({
    checked: true,
});

storiesOf('Toggle', module)
    .addDecorator(StateDecorator(store))
    .add('', () => (
        <Toggle name="toggle" onChange={() => store.set({checked: store.get('checked')})} />
    ))

Upvotes: 2

Related Questions