generate table in react in typescript

To generate a table in React with TypeScript, we can use the JSX syntax and create a functional component that accepts data as props. Here is some sample code:

import React from "react";

interface TableProps {
  data: any[];
}

const Table: React.FC<TableProps> = ({ data }) => {
  return (
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        {data.map(({ id, name, email }) => (
          <tr key={id}>
            <td>{id}</td>
            <td>{name}</td>
            <td>{email}</td>
          </tr>
        ))}
      </tbody>
    </table>
  );
};

export default Table;
524 chars
31 lines

In this example, we define a TableProps interface that specifies the type of the data prop.

We then define a functional component Table that accepts the data prop, which is an array of objects with id, name and email fields.

Inside the Table component, we use the JSX syntax to create a HTML table element with a header row and a body that loops over the data array using the .map() function to generate a row for each object in the array.

Note the use of the key attribute in the tr element, which helps React to efficiently update the table when the data changes.

Finally, we export the Table component as default to be used in other parts of the application.

related categories

gistlibby LogSnag