Visualizzazione di un array di oggetti come tabella HTML in React
Supponiamo di avere nuovamente il nostro array di prodotti:
const prods = [
{id: 1, name: 'product1', cost: 100},
{id: 2, name: 'product2', cost: 200},
{id: 3, name: 'product3', cost: 300},
];
Visualizziamo gli elementi del nostro array come una tabella HTML:
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>;
}
Aggiungiamo le intestazioni delle colonne alla nostra tabella:
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>nome</td>
<td>costo</td>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>;
}
Nel componente App è dato il seguente array:
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},
];
Visualizza gli elementi di questo array come tabella
table in modo che ogni campo dell'oggetto
finisca nel suo tag td. Crea le intestazioni
delle colonne della tua tabella.