D Park
D Park

Reputation: 514

Material UI <TableCell> component does not dynamically render dataset

I am trying to create a table component that dynamically renders the item list based on dataset. The Table component consists of <TableHead/> and <TableBody/> I use .map() to dynamically create assign values to <TableCell/> component.

const data = [{
      new_cases: 100,
      total_cases: 200,
      province: 'Ontario'
    }, 
    {
      new_cases: 300,
      total_cases: 400,
      province: 'Edmonton'
    }]

const CustomTable = () => {
    const tableHead = Object.getOwnPropertyNames(data[0]);

   return (
    <TableContainer>
        <TableHead>
            <TableRow>
                {tableHead.map(name => <TableCell>{name}</TableCell>)}
            </TableRow>
        </TableHead>
        <TableBody>
                {data.forEach(row => (
                    <TableRow>
                        {Object.values(row).map(column => (
                            <TableCell>{column}</TableCell>
                        ))}
                    </TableRow>)
                )}
            </TableBody>
      <TableContainer>
    );
};

export default CustomTable;

However, the problem is that the <TableCell/> wrapped in <TableBody/> does not display column value. What is weird is that it properly returns property values when I console.log(column) Am I missing anything?

<TableRow>
    {Object.values(row).map(column => <TableCell>{column}</TableCell>)}
</TableRow>)
//TableCell is not rendered.
<TableRow>
    {Object.values(row).map(column => console.log(column))}
</TableRow>
//returns 100, 200, 'Ontario', 300, 400,'Edmonton'

Upvotes: 0

Views: 537

Answers (1)

keikai
keikai

Reputation: 15176

You may want to change the forEach to map.

{data.forEach(row => (

to

{data.map(row => (

Upvotes: 1

Related Questions