Skip to content

Contact sales

By filling out this form and clicking submit, you acknowledge our privacy policy.

How to Iterate Through a Component's Children in React Typescript

Aug 18, 2020 • 5 Minute Read

Introduction

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.

Creating Components With TypeScript Type Checking

Start by creating the main App component.

      class App extends React.Component<{}, AppState> {
  //...
}
    

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.

      export default interface User {
  id: number;
  name: string;
  avatar: string;
}
    

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.

      import React from "react";

import UserInterface from "User.interface.tsx";

interface AppState {
  users: UserInterface[];
}

class App extends React.Component<{}, AppState> {
  constructor(props: any) {
    super(props);

    this.state = {
      users: [],
    };
  }

  render() {
    // ...
  }
}
    

To render a single user on the web page, create a User component.

      import React, { Component } from "react";

import UserInterface from "../User.interface.tsx";

const User = ({ id, name, avatar }: UserInterface) => (
  <div className="user-container" data-id={id}>
    <img src={avatar} className="user-avatar" />
    <span className="user-name">{name}</span>
  </div>
);

export default User;
    

Fetching Data And Assigning State

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.

      class App extends React.Component<{}, AppState> {
  constructor(props: any) {
    super(props);

    this.state = {
      users: [],
    };
  }

  componentDidMount() {
    const URL = `some-user-endpoint-for-fetching-users`; // in a real world example this would be a valid URL
    fetch(URL)
      .then((res) => res.json())
      .then((data) =>
        this.setState({
          users: data.users,
        })
      );
  }

  render() {
    // ...
  }
}
    

Using Map To Iterate Over a User's State

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.

      // ...

import User from "./components/User";

class App extends React.Component<{}, AppState> {
  constructor(props: any) {
    super(props);

    this.state = {
      users: [],
    };
  }

  componentDidMount() {
    const URL = `some-user-endpoint-for-fetching-users`;
    fetch(URL)
      .then((res) => res.json())
      .then((data) =>
        this.setState({
          users: data.users,
        })
      );
  }

  render() {
    return (
      <div className="users">
        {this.state.users.map((user: UserInterface) => (
          <User {...user} />
        ))}
      </div>
    );
  }
}
    

Below is a shorthand version for assigning the props.

      <User {...user} />
    

The above syntax infers the same as follows.

      <User id={user.id} name={user.name} avatar={user.avatar} />
    

Iterating Through A Component's Children

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.

      import React from "react";
import UserInterface from "User.interface.tsx";

interface AppProps {
  children: React.ReactElement<UserInterface>[];
}

class App extends React.Component<AppProps, {}> {
  render() {
    return this.props.children.map(
      (child: React.ReactElement<UserInterface>) => (
        <div>{child.props.name}</div>
      )
    );
  }
}
    

Conclusion

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.

Gaurav Singhal

Gaurav S.

Guarav is a Data Scientist with a strong background in computer science and mathematics. He has extensive research experience in data structures, statistical data analysis, and mathematical modeling. With a solid background in Web development he works with Python, JAVA, Django, HTML, Struts, Hibernate, Vaadin, Web Scrapping, Angular, and React. His data science skills include Python, Matplotlib, Tensorflows, Pandas, Numpy, Keras, CNN, ANN, NLP, Recommenders, Predictive analysis. He has built systems that have used both basic machine learning algorithms and complex deep neural network. He has worked in many data science projects, some of them are product recommendation, user sentiments, twitter bots, information retrieval, predictive analysis, data mining, image segmentation, SVMs, RandomForest etc.

More about this author