Skip to main content

TypeScript & React

In this tutorial, we will explore how to use TypeScript with React to build strongly typed components, improving code quality and maintainability.

TypeScript with React

Using TypeScript with React enables you to leverage TypeScript's strong typing capabilities for building components. By typing your component's props and state, you can catch errors at compile-time, reducing runtime errors and making your code more maintainable.

Creating a Typed Functional Component

To create a typed functional component, you can use the React.FC type for your component and define the props using an interface or a type.

TypeScript
import React from 'react';

interface ButtonProps {
text: string;
onClick: () => void;
}

const Button: React.FC<ButtonProps> = ({ text, onClick }) => {
return <button onClick={onClick}>{text}</button>;
};

export default Button;

In this example, we define a Button component that accepts text and onClick props. By using the React.FC<ButtonProps> type, we ensure that the component only accepts valid props.

Creating a Typed Class Component

To create a typed class component, you can extend React.Component and provide the props and state types as type parameters.

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

interface CounterProps {
initialCount: number;
}

interface CounterState {
count: number;
}

class Counter extends Component<CounterProps, CounterState> {
constructor(props: CounterProps) {
super(props);
this.state = {
count: props.initialCount,
};
}

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

render() {
return (
<div>
<h2>Count: {this.state.count}</h2>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}

export default Counter;

In this example, we define a Counter class component that accepts initialCount as a prop and maintains a count state. By extending React.Component<CounterProps, CounterState>, we ensure that the component uses the correct types for props and state.

Conclusion

In this tutorial, we have explored how to use TypeScript with React to build strongly typed components, improving code quality and maintainability. As you continue learning TypeScript and React, consider using TypeScript for your React projects to enforce strong typing and reduce errors.