Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features
Autoplay

    Refactor a React TypeScript Function Component into a Class Component with defaultProps

    Shawn WangShawn Wang
    reactReact
    typescriptTypeScript

    In this lesson we see how to refactor a function component into a class component with typed props and state as well as defaultProps.

    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
    Transcript

    Transcript

    Instructor: 00:00 Let's take this function component and refactor it to a class component to learn how that's done in TypeScript. We're going to extend React.Component. We're going to wrap the render around the return. We still have to destructure the label.

    00:19 Now we come to a problem because label doesn't exist on the props. We've removed the props that we've manually typed. There's no way to insert it. Fortunately, the place to put it is in React.Component where the TypeScript typings define generics for you to overwrite. Generic, let's feed in the props as the first argument.

    00:47 Now you can see that it expects label as a prop. To prevent a lot of destructuring, you can move the defaultProps up to the static defaultProps property and define it over there. Now let's also add some state to our component. We'll add another type and call it MyState. We'll have an isOn Boolean. We'll pass that in as the second argument to React.Component's generics.

    01:24 Now we'll have to define the state somewhere, isOn being true from the beginning. Now we can take that isOn from this.props, and we can create some styles based on it. I'm going to give the button a background color based on whether the button is on or off, so green if it's on, red if it's off. We can pass that into the style.

    02:06 Now we're pulling in some state, and the state is properly typed, but we also need to be able to write an event handler. We'll call this toggle this.setState({isOn: ! This.state.isOn}). We'll toggle the state of it. We'll pass that into the button's onClick method, this.toggle. Now we have a working toggle.

    Discuss

    Discuss