Home > OS >  How to render an array of objects inside a table body using .map() in React
How to render an array of objects inside a table body using .map() in React

Time:02-04

I have an array of data, theData, that looks like this:

const theData = [
    {
        student_id: 2,
        firstName: 'John',
        subject: 'Physics',
        grade:  90
    },
    {
        student_id: 14,
        firstName: 'Sally',
        subject: 'Biology',
        grade: 95
    },
    {
        student_id: 17,
        firstName: 'Roger',
        subject: 'Calculus',
        grade: 87
    },
    {
        student_id: 83,
        firstName: 'Mary',
        subject: 'Computer Science',
        grade: 99
    }]

I'd like to render this data in tabular form using React.

I can render the first row of the table using the following:

import {TableContainer, Table, TableHead, TableRow, TableCell, TableBody} from '@mui/material';

  <TableContainer>
    <Table>
      <TableHead>
        <TableRow>
          <TableCell key='FirstName'>FirstName</TableCell>
          <TableCell key='Subject'>Subject</TableCell>
          <TableCell key='Grade'>Grade</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {
          <TableRow key={theData[0].student_id}>
            <TableCell key='firstName'>{theData[0].firstName}</TableCell>
            <TableCell key='Subject'>{theData[0].subject}</TableCell>
            <TableCell key='Grade'>{theData[0].grade}</TableCell>
          </TableRow>
        }
      </TableBody>
    </Table>
  </TableContainer>

Which results in this table:

firstName       subject        grade
John            Physics        90

How would I render the entire table using the .map() function inside the TableBody element?

CodePudding user response:

With something like this

import {TableContainer, Table, TableHead, TableRow, TableCell, TableBody} from '@mui/material';

  <TableContainer>
    <Table>
      <TableHead>
        <TableRow>
          <TableCell key='FirstName'>FirstName</TableCell>
          <TableCell key='Subject'>Subject</TableCell>
          <TableCell key='Grade'>Grade</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        {theData.map(row =>
          <TableRow key={row.student_id}>
            <TableCell key='firstName'>{row.firstName}</TableCell>
            <TableCell key='Subject'>{row.subject}</TableCell>
            <TableCell key='Grade'>{row.grade}</TableCell>
          </TableRow>
        )}
      </TableBody>
    </Table>
  </TableContainer>

CodePudding user response:

Map directly in TableBody

<TableBody>
  {theData.map((item) => {
    return (
      <TableRow key={item.student_id}>
        <TableCell key="firstName">{item.firstName}</TableCell>
        <TableCell key="Subject">{item.subject}</TableCell>
        <TableCell key="Grade">{item.grade}</TableCell>
      </TableRow>
    );
  })}
</TableBody>;
  • Related