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

Shawn Wang
InstructorShawn Wang
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years 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.

egghead
egghead
~ 4 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today