Why I cannot map over this array of objects in React JS?
Here’s my code:
JavaScript
x
24
24
1
const columns = [
2
{ field: 'id', headerName: 'ID', width: 200 },
3
{ field: 'season', headerName: 'Season', width: 200 },
4
{ field: 'transferWindow', headerName: 'Transfer Window', width: 200 }
5
]
6
<table>
7
<thead>
8
<tr>
9
{columns.map((item) => {
10
<th key={item.field}>{item.field}</th>
11
})}
12
13
{/* <th>{columns[0].field}</th>
14
<th>{columns[1].field}</th>
15
<th>{columns[2].field}</th> */}
16
</tr>
17
</thead>
18
<tbody>
19
<tr>
20
<td></td>
21
</tr>
22
</tbody>
23
</table>
24
The code in quotations is working but map is not.
Advertisement
Answer
You are missing a return statement on the map so you are not able to get the output.
You can do it as follows.
JavaScript
1
26
26
1
export default function App() {
2
const columns = [
3
{ field: "id", headerName: "ID", width: 200 },
4
{ field: "season", headerName: "Season", width: 200 },
5
{ field: "transferWindow", headerName: "Transfer Window", width: 200 }
6
];
7
return (
8
<div className="App">
9
<table>
10
<thead>
11
<tr>
12
{columns.map((item) => (
13
<th key={item.field}>{item.field}</th>
14
))}
15
</tr>
16
</thead>
17
<tbody>
18
<tr>
19
<td></td>
20
</tr>
21
</tbody>
22
</table>
23
</div>
24
);
25
}
26