Search code examples
reactjstypescriptreact-bootstrap

React Typescript list mapped table row not rendering


I have a list of objects called items. I want to each object in the list to a row in the table. However, the rows are not being rendered. I'm using typescript with react-bootstrap. I'm wondering why this happened and how to fix it. Thanks!

Template.tsx

export default function Templates() {
    const items = [
        {
          "name": "Item 1",
          "alt": "First",
          "description": "This is the first item"
        },
        {
          "name": "Item 2",
          "alt": "Second",
          "description": "This is the second item"
        },
        {
          "name": "Item 3",
          "alt": "Third",
          "description": "-"
        }
      ]
    return (
        <>
            <MyTable items={items}>MyTable</MyTable>
        </>
    )
}

MyTable.tsx

import React from 'react'
import { Table, Button } from 'react-bootstrap'

type TableProps = {
    items: {
        name: string,
        alt: string,
        description: string
    }[]
}
const MyTable: React.FunctionComponent<TableProps> = ({
    items
  }) => {
    return (
        <>
            <Table striped bordered hover variant="dark">
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Alt</th>
                        <th>Description</th>
                    </tr>
                </thead>
                <tbody>
                    {items.map(item => {
                        <tr>
                            <td>{item.name}</td>
                            <td>{item.alt}</td>
                            <td>{item.description}</td>
                        </tr>
                    })}
                </tbody>
            </Table>
        </>
        )
  };

export default MyTable;

Right now only the thead are being rendered.


Solution

  • you are maping over the items and the map callback return undefined(no return statment),make sure to return the iterated item:

         {items.map(item => {
              return (
                <tr key={item.name}>
                  <td>{item.name}</td>
                  <td>{item.alt}</td>
                  <td>{item.description}</td>
                </tr>
              )
            })}