Skip to main content

TypeScript with Class Components

In this tutorial, you will learn how to use TypeScript with class components in React. We will cover type annotations for props and state, as well as best practices for using TypeScript in class components.

Type annotations for props

When using TypeScript with React class components, you can add type annotations to define the expected types for props. Here's an example of a class component with TypeScript:

JavaScript
import React, { Component } from 'react';

type Props = {
message: string;
};

class Greeting extends Component<Props> {
render() {
const { message } = this.props;
return <h1>{message}</h1>;
}
}

export default Greeting;

In this example, we define a Props type for the component's props. The Greeting component then extends Component<Props> to specify the expected prop types.

Type annotations for state

You can also add type annotations for the component's state. Here's an example:

JavaScript
import React, { Component } from 'react';

type Props = {
message: string,
};

type State = {
counter: number,
};

class Counter extends Component<Props, State> {
state: State = {
counter: 0,
};

increment = () => {
this.setState(prevState => ({ counter: prevState.counter + 1 }));
};

render() {
const { message } = this.props;
const { counter } = this.state;

return (
<div>
<h1>{message}</h1>
<p>Counter: {counter}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}

export default Counter;

In this example, we define a State type for the component's state. The Counter component then extends Component<Props, State> to specify the expected prop and state types.

Event handlers

When using event handlers in class components, you can add type annotations to ensure the correct event types are used:

JavaScript
import React, { Component, MouseEvent } from 'react';

type Props = {
message: string,
};

class Button extends Component<Props> {
handleClick = (event: MouseEvent<HTMLButtonElement>) => {
console.log('Button clicked');
};

render() {
const { message } = this.props;
return <button onClick={this.handleClick}>{message}</button>;
}
}

export default Button;

In this example, we use the MouseEvent type from React to specify that the handleClick method should handle a MouseEvent with HTMLButtonElement as its target.

Conclusion

Now you know how to use TypeScript with class components in React. Remember to define prop and state types using type annotations and specify event types for event handlers. These best practices will help you write safer, more maintainable code.