React does not come with a type-check system out of the box. When working on a complex or huge enterprise-level application, you probably want to write better code that can be unit tested, type-checked, and debugged easily. TypeScript is a compiled superset of JavaScript that can do just that.
In this guide, you will get a quick overview of how to use TypeScript with React and learn to enforce type checks inside a React component.
Start by creating the main App
component.
1class App extends React.Component<{}, AppState> {
2 //...
3}
For this example, you will fetch a list of users from an endpoint and display it on the frontend. To type check the user entity, create an interface called User
in the User.interface.tsx
file.
1export default interface User {
2 id: number;
3 name: string;
4 avatar: string;
5}
Next, create an AppState
interface to type check the state in the App
component.
Add a "allowSyntheticDefaultImports": true
line in the tsconfig
file to use the import statements similar to regular jsx.
1import React from "react";
2
3import UserInterface from "User.interface.tsx";
4
5interface AppState {
6 users: UserInterface[];
7}
8
9class App extends React.Component<{}, AppState> {
10 constructor(props: any) {
11 super(props);
12
13 this.state = {
14 users: [],
15 };
16 }
17
18 render() {
19 // ...
20 }
21}
To render a single user on the web page, create a User
component.
1import React, { Component } from "react";
2
3import UserInterface from "../User.interface.tsx";
4
5const User = ({ id, name, avatar }: UserInterface) => (
6 <div className="user-container" data-id={id}>
7 <img src={avatar} className="user-avatar" />
8 <span className="user-name">{name}</span>
9 </div>
10);
11
12export default User;
In the componentDidMount
lifecycle method, get the users list from the backend server using the browser Fetch API. As shown below, pass the user's entity URL to the fetch
method, and once the JSON response is ready to be used, set the users in the state.
1class App extends React.Component<{}, AppState> {
2 constructor(props: any) {
3 super(props);
4
5 this.state = {
6 users: [],
7 };
8 }
9
10 componentDidMount() {
11 const URL = `some-user-endpoint-for-fetching-users`; // in a real world example this would be a valid URL
12 fetch(URL)
13 .then((res) => res.json())
14 .then((data) =>
15 this.setState({
16 users: data.users,
17 })
18 );
19 }
20
21 render() {
22 // ...
23 }
24}
The map
method can be used to iterate over an array. To leverage type checking, use the UserInterface
to type check each child in the user array.
1// ...
2
3import User from "./components/User";
4
5class App extends React.Component<{}, AppState> {
6 constructor(props: any) {
7 super(props);
8
9 this.state = {
10 users: [],
11 };
12 }
13
14 componentDidMount() {
15 const URL = `some-user-endpoint-for-fetching-users`;
16 fetch(URL)
17 .then((res) => res.json())
18 .then((data) =>
19 this.setState({
20 users: data.users,
21 })
22 );
23 }
24
25 render() {
26 return (
27 <div className="users">
28 {this.state.users.map((user: UserInterface) => (
29 <User {...user} />
30 ))}
31 </div>
32 );
33 }
34}
Below is a shorthand version for assigning the props.
1<User {...user} />
The above syntax infers the same as follows.
1<User id={user.id} name={user.name} avatar={user.avatar} />
Iterating through a component's children is the same as any other array. Use the map
method in this case as well. To type check the child, use React.ReactElement
type, along with the type for the child's props. In this case, it is UserInterface
.
1import React from "react";
2import UserInterface from "User.interface.tsx";
3
4interface AppProps {
5 children: React.ReactElement<UserInterface>[];
6}
7
8class App extends React.Component<AppProps, {}> {
9 render() {
10 return this.props.children.map(
11 (child: React.ReactElement<UserInterface>) => (
12 <div>{child.props.name}</div>
13 )
14 );
15 }
16}
TypeScript is an excellent utility that can be used to create a type-checked codebase. This will help in debugging further issues and save a lot of time in solving runtime errors during the app development lifecycle. For iterating over an array, use the map
, forEach
, reduce
, filter
, etc. methods; each method has a different purpose. To fetch data from an external source, you can use Axios, as well.
That's it from this guide. Keep learning.