September 20, 2022

Storybook With React & TypeScript

Tech
Storybook With React & TypeScript

I've really enjoyed working with the component library platform Storybook, because it not only fulfills its promise of providing a rich and interactive documentation of your UI components, but also serves as a workshop for building and iterating on them. I feel like Storybook is a compelling alternative to unit testing your components, driving many of the same outcomes: reusability, intuitive and clean component design, and self-documentation.

If you're using React & TypeScript, and a component library like MUI, then Storybook becomes even more powerful -- but not right out of the box. Let's walk through how I've unlocked the full potential of Storybook with this combination of technologies through the lens of a simple Button component.

Inheriting All Of The Props

By default, Storybook will only display the props explicitly defined in your component's types, or in your `stories.tsx` file's `args`. The component file and stories files above yield this Storybook page:

Just a single control: label

That's not very helpful! There are many more props at our disposal from MUI. Let's leverage the MUI Button component's TypeScript prop types to grab more of them.

Great! Now we should have 25 controls in Storybook, instead of just 1.

Much better!

Configuring Storybook Settings

Extending the prop interfaces of your components with MUI prop types makes the biggest difference, but there are a few additional things that you may need to configure in your .storybook/main.js file regarding TypeScript. The following steps may be optional.

There are some sub-component props and other inherited props that these settings will provide for you, try this out if you feel like you're missing props:

There are a lot of props that we don't necessarily want to display in Storybook, here are the props that I'm choosing to hide at the config level.

Now we're up to 39 props that we can control!

Here's the final product of what your Button component should look like in Storybook!

This could also be interesting for you