TypeScript with Functional Components
In this tutorial, you will learn how to use TypeScript with functional components in React. We will cover type annotations, prop types, and best practices.
Type annotations for functional components
When using TypeScript with React functional components, you can add type annotations to define the expected types for props and return values.
Here is an example of a functional component with TypeScript:
import React, { FC } from 'react';
type Props = {
message: string,
};
const Greeting: FC<Props> = ({ message }) => {
return <h1>{message}</h1>;
};
export default Greeting;
In this example, we use the FC
(Function Component) type from the React library to define the type of our Greeting
component. FC<Props>
is a generic type that expects the Props
type as its argument.
We also define a Props
type for the component's props. In this case, the component expects a message
prop of type string
.
Optional props
You can make a prop optional by adding a ?
after the prop name in the type definition:
import React, { FC } from 'react';
type Props = {
message?: string,
};
const Greeting: FC<Props> = ({ message = 'Hello!' }) => {
return <h1>{message}</h1>;
};
export default Greeting;
Now the message
prop is optional, and we provide a default value for it in the component's destructuring assignment.
Type annotations for event handlers
When using event handlers in functional components, you can add type annotations to ensure the correct event types are used:
import React, { FC, MouseEvent } from 'react';
type Props = {
onClick: (event: MouseEvent<HTMLButtonElement>) => void;
};
const Button: FC<Props> = ({ onClick }) => {
return <button onClick={onClick}>Click me</button>;
};
export default Button;
In this example, we use the MouseEvent
type from React to specify that the onClick
prop should be a function that takes a MouseEvent
with HTMLButtonElement
as its target.
Conclusion
Now you know how to use TypeScript with functional components in React. Remember to define prop types using type annotations, make optional props clear, and specify event types for event handlers. These best practices will help you write safer, more maintainable code.