Outputting an Array of Objects as an HTML Table in React
Let us again be given our array of products:
const prods = [
{id: 1, name: 'product1', cost: 100},
{id: 2, name: 'product2', cost: 200},
{id: 3, name: 'product3', cost: 300},
];
Let's output the elements of our array as an HTML table:
function App() {
const rows = prods.map(function(item) {
return <tr key={item.id}>
<td>{item.name}</td>
<td>{item.cost}</td>
</tr>;
});
return <table>
<tbody>
{rows}
</tbody>
</table>;
}
Let's add column headings to our table:
function App() {
const rows = prods.map(function(item) {
return <tr key={item.id}>
<td>{item.name}</td>
<td>{item.cost}</td>
</tr>;
});
return <table>
<thead>
<tr>
<td>Name name title designation denomination appellation denotation appellative</td>
<td>price value cost worth purchase denomination val damage</td>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>;
}
In the App component the following array is given:
const users = [
{id: 1, name: 'user1', surn: 'surn1', age: 30},
{id: 2, name: 'user2', surn: 'surn2', age: 31},
{id: 3, name: 'user3', surn: 'surn3', age: 32},
];
Output the elements of this array as a table table so that each field of the object gets into its own tag td. Make the column headings of your table.