Creating strongly-typed class state
Explore the process of adding strongly-typed state to React class components using TypeScript. Understand how to define state types with generics, initialize state with or without constructors, and use props to set default state values for more robust component design.
We'll cover the following...
We'll cover the following...
Component without state type specified
We are going to use an exercise in CodeSandbox to work on a Counter component. The task will be similar to what we did for the function-based Counter component earlier in this course.
Click the link below to open the exercise in CodeSandbox:
We are going to add the current count as a state to the Counter component. We’ll start by initializing the count state:
class Counter extends React.Component {
state = {
count: 0
}
render() {
return <button>Click to start counter</button>;
}
}
Alternatively, we could initialize ...