React Functional Components with TypeScript
React is a popular JavaScript library for building user interfaces, and with the addition of TypeScript, it provides a type-safe approach to coding UI components. In this article, we'll cover the basics of creating React functional components using TypeScript and show some code examples.
What are React Functional Components?
Functional components are a simpler way to write React components. They are stateless and only return the markup that is to be displayed on the screen. They don’t have lifecycle methods or local state, but they can receive and render props passed from a parent component.
Functional components are declared using a plain JavaScript function that returns a React element, or in other words, the markup that is to be displayed on the screen.
Why use TypeScript with React?
TypeScript is a statically-typed superset of JavaScript that provides optional type checking and better tooling support. It makes it easier to catch type-related errors during development and helps to maintain the quality of code over time. TypeScript also provides better IntelliSense support and helps to keep the code maintainable, especially in large projects.
Creating a Functional Component in TypeScript
Let's create a simple functional component that displays a message. We'll call this component "HelloWorld".
import React from 'react';
interface Props {
message: string;
}
const HelloWorld: React.FC<Props> = ({ message }) => {
return <div>{message}</div>;
};
export default HelloWorld;
Here, we start by importing React and declaring an interface for the props that the component will receive. The interface Props
has a single property message
of type string.
Next, we declare the functional component using the React.FC
generic type, which stands for "Functional Component." This type allows us to specify the type of props that the component will receive using angle brackets. In this case, the component will receive props of type Props
.
Finally, we return the message inside a div element.
Using the Functional Component
Now that we have created the HelloWorld component, let's see how we can use it in another component.
import React from 'react';
import HelloWorld from './HelloWorld';
const App: React.FC = () => {
return (
<div>
<HelloWorld message="Hello, World!" />
</div>
);
};
export default App;
Here, we import the HelloWorld component and render it inside a div element. We pass the message "Hello, World!" as a prop to the component.
Rendering a List of Items
Let's create another component that renders a list of items. We'll call this component "List".
import React from 'react';
interface Item {
id: number;
name: string;
}
interface Props {
items: Item[];
}
const List: React.FC<Props> = ({ items }) => {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
export default List;
In this example, we start by declaring an interface for the items that will be rendered in
State Management in React with TypeScript
In addition to functional components, React also provides a way to manage state within components. State is an object that holds data that can change over time, and is used to update the UI whenever the state changes.
TypeScript provides a type-safe approach to managing state in React components. To manage state in a functional component, we can use the useState hook.
import React, { useState } from 'react';
interface Props {
message: string;
}
const HelloWorld: React.FC<Props> = ({ message }) => {
const [count, setCount] = useState(0);
return (
<div>
{message} {count}
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
};
export default HelloWorld;
In this example, we import the useState hook from the React library and use it to manage a local state called count
. The useState hook returns an array with two values: the current state, and a function to update the state. We destructure the array into two variables, count
and setCount
.
We display the current value of count
in the UI, and we use a button element with an onClick handler that updates the count whenever it's clicked.
Class Components with TypeScript
In addition to functional components, React also provides a way to create components using class-based components. Class components provide additional features such as lifecycle methods and local state, but they are also more verbose than functional components.
TypeScript provides a type-safe approach to coding class components. Let's see an example:
import React, { Component } from 'react';
interface Props {
message: string;
}
interface State {
count: number;
}
class HelloWorld extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
count: 0
};
}
render() {
const { message } = this.props;
const { count } = this.state;
return (
<div>
{message} {count}
<button onClick={() => this.setState({ count: count + 1 })}>
Click me
</button>
</div>
);
}
}
export default HelloWorld;
Here, we start by extending the React Component class and providing the Props and State interfaces as type arguments. The Props interface is used to define the props that the component will receive, and the State interface is used to define the local state.
In the constructor, we call the super
constructor and pass the props, and we initialize the local state with an object that has a single property called count
.
In the render
method, we destructure the props and state and display their values in the UI. We also use a button element with an onClick handler that updates the count whenever it's clicked.
Conclusion
In this article, we have covered the basics of creating React functional components with TypeScript, as well as state management and class components. TypeScript provides a type-safe approach to coding React components, making it easier to catch type-related errors and maintain the quality of
Popular questions
- What is a functional component in React and how does TypeScript work with it?
A functional component in React is a simple, stateless, and reusable component that is defined as a function. TypeScript provides a type-safe approach to coding functional components, making it easier to catch type-related errors and maintain the quality of the code.
- What is the useState hook and how is it used in React functional components with TypeScript?
The useState
hook is a way to manage state within functional components in React. It returns an array with two values: the current state and a function to update the state. TypeScript can be used to provide type annotations for the state and its update function, making it easier to catch type-related errors.
- How do you create class components with TypeScript in React?
To create class components with TypeScript in React, you extend the Component
class from the React library and provide the Props
and State
interfaces as type arguments. The Props
interface is used to define the props that the component will receive, and the State
interface is used to define the local state. TypeScript provides type annotations for props and state, making it easier to catch type-related errors.
- What is the purpose of the
render
method in a class component in React with TypeScript?
The render
method in a class component in React with TypeScript is used to define the structure of the component and its content. It returns a tree of React elements, which will eventually be rendered to the DOM. The render
method can access both props and state, and can use TypeScript type annotations to catch type-related errors.
- Can functional components in React with TypeScript replace class components?
Yes, functional components in React with TypeScript can replace class components in many cases. Functional components are simpler, faster, and easier to understand than class components, and they are often sufficient for small and stateless components. However, class components are still useful in cases where you need more advanced features such as lifecycle methods and local state. Ultimately, the choice between functional and class components depends on the specific needs of your project.
Tag
ReactFCTS