Typing the props and state of React class based components
Similar to how things are done for functional components in classes we can use a mix of Typescript’s inference and our own interfaces.
To type the props we need to declare an interface and then pass that interface as parameter to the generic React Component class:
class UserSearch extends Component<UserSearchProps>
Then we can define extra interfaces and use those to type everything we need in the state.
state: UserSearchState = {
name: '',
user: undefined
}
The gist below shows a full implementation of a class based component with typed props and state.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from 'react' | |
interface User { | |
name: string; | |
age: number; | |
} | |
interface UserSearchProps { | |
users: User[] | |
} | |
interface UserSearchState { | |
name: string; | |
user: User | undefined | |
} | |
class UserSearch extends Component<UserSearchProps> { | |
state: UserSearchState = { | |
name: '', | |
user: undefined | |
} | |
onSearch = () => { | |
const foundUser = this.props.users.find((u) => u.name.toLowerCase().includes(this.state.name.toLowerCase())); | |
this.setState({ user: foundUser }); | |
}; | |
render() { | |
const { user, name } = this.state | |
return ( | |
<div> | |
<h1>User search</h1> | |
<input value={name} onChange={(e) => this.setState({ name: e.target.value })} /> | |
<button onClick={this.onSearch}>Search</button> | |
<div>{user && user.name}</div> | |
</div> | |
); | |
} | |
} | |
export default UserSearch |