🎁

12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
15 : 05 : 51 : 41
1×
Become a member
to unlock all features
Autoplay

    Configure React Storybook for use with Typescript

    Shawn WangShawn Wang
    reactReact
    ^16.0.0
    webpackwebpack
    react-storybookReact Storybook
    ^3.0.0
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.