Configure React Storybook for use with Typescript

Shawn Wang
InstructorShawn Wang
Share this video with your friends

Social Share Links

Send Tweet

Storybook is a UI component development environment for React, Vue, and Angular. With that, you can develop UI components without running your app.

Here I show how best to configure a React Storybook to use Typescript (with TSX). This lets you write your reusable components with maximal type safety. Please see the provided code for the full source.

Instructor: [00:00] We are going to add two new files, webpack.config.js in the special storybook folder, and tsconfig.json. We're also going to add a couple of new dependencies, the types definition for react, typescript, and the typescript loader. We're going to head to tsconfig.json and set up the typical tsconfig. The main thing to take note of is to have the jsx field set to react.

[00:23] Now, we're going to head to set up the webpack config inside Storybook. The webpack config requires a special format where they pass you the Storybook's internal webpack config. We're going to use the full config mode to customize it.

[00:40] We take Storybook's default config and we modify it by pushing on extra rules on top of the rules it already has. For ts and tsx files, we're going to require that it use TypeScript loader and also make it recognize ts and tsx files. Make sure to also return default.config at the end.

[01:00] Now that our Storybook can speak TypeScript, it's time to upgrade or button our js file into a tsx file. I've rewritten our button component into a TypeScript React component with extra props with types. You can also add some custom CSS just to make styling look better. Now, when you run Storybook, this is what you should see.

[01:24] Now, if you set up your knobs for your story -- for example, here in the second story I have set up the Boolean knob for the disabled prop which just takes true or false, as well as the text knob for the child text property -- I can also play with them here. For example, here I'm toggling on and off the disabled field, as well as editing the text field.