Afișarea unui tablou de obiecte sub formă de tabel HTML în React
Să presupunem că avem din nou tabloul nostru cu produse:
const prods = [
{id: 1, name: 'product1', cost: 100},
{id: 2, name: 'product2', cost: 200},
{id: 3, name: 'product3', cost: 300},
];
Să afișăm elementele tabloului nostru sub formă de tabel 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>;
}
Să adăugăm antetele coloanelor în tabelul nostru:
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>nume</td>
<td>cost</td>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>;
}
În componenta App este dat următorul tablou:
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},
];
Afișați elementele acestui tablou sub formă de tabel
table astfel încât fiecare câmp al obiectului
să ajungă în propriul său tag td. Faceți antetele
coloanelor tabelului dvs.