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

Shawn Wang
InstructorShawn Wang

Share this video with your friends

Send Tweet
Published 3 years ago
Updated a year ago

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

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.