Enable a Storybook control conditionally

Viewed 2899

I use controls in a story to see different states of a component. Some props only make sense if some other prop is enabled.

For example, I have 3 props:

  • isEmployee - boolean
  • isActive - boolean
  • canContactInTheWeekend - boolean

Here, canContactInTheWeekend applies only if isActive is true. To make it more clear for a developer, I'd like to disable canContactInTheWeekend toggle when isActive is false.

How can I achieve it with standard Storybook setup or via some plugins?

2 Answers

This issue was exactly the motivation for Flare, a principled alternative to Storybook Knobs and Storybook Controls. Here is how I would implement your example using Flare:

pipe(
  of((isEmployee: boolean) => (otherProps: { isActive: boolean, canContactInTheWeekend: boolean }) => (<Contact {...{ isEmployee, ...otherProps }} />)),
  ap(checkbox({ label: "Employee", initial: false })),
  ap(
    pipe(
      switch_({ label: "Active", initial: false }),
      chain(ifElse(
        pipe(
          checkbox({ label: "Weekend OK", initial: false }),
          map(canContactInTheWeekend => ({ isActive: true, canContactInTheWeekend }))
        ),
        of({ isActive: false, canContactInTheWeekend: false })
      ))
    )
  )
)

Here's a complete working demo: https://codesandbox.io/s/gifted-paper-ulqrg?file=/src/main.tsx:719-1276

For more info about Flare, check out https://flare.js.org/

Note that I'm the author.

Related