Problem:
I have to create an HTML table from an array of objects I receive from an API call. I am using react. Here is the relevant code
return(
</Container>
{((demoLedgerEntries.length > 0) &&
<Table>
<thead>
<tr><td>Title demo</td><td>Title demo</td><td>Title demo</td></tr>
</thead>
<tbody>
<tr><td>itemdemo1</td><td>itemdemo1</td><td>itemdemo1</td></tr>
{demoLedgerEntries.forEach((item) => {
return(<tr><td>{item.name}</td> </tr>)
})
}
<tr><td>itemdemo2</td><td>itemdemo2</td><td>itemdemo2</td></tr>
</tbody>
</Table>
)
}
</Container>
)
The demoLedgerEntries is an array of objects as follows.
setDemoLedgerEntries([
{ name: 'Player 1', score: 10 },
{ name: 'Player 2', score: 7 },
{ name: 'Player 3', score: 3 }]
);
The resulting table only has the head row, the first row and the last row. The forEach loop for the array is not producing any elements. How do I modify the code to make it work?
Solution:
Like Hamms said in his comment you can use map to go through elements of demoLadgerEntries
array, so your code will look something like this:
{demoLedgerEntries.map((item) => (
<tr>
<td>{item.wagerAmount}</td>
</tr>
))}
or maybe this is what you want:
<tr>
{demoLedgerEntries.map((item) => (
<td>{item.wagerAmount}</td>
))}
</tr>
Also, I don’t see wagerAmount
in elements of your demoLadgerEntries
array.