Skip to content
Advertisement

Why I cannot map over this array of objects in React JS?

Why I cannot map over this array of objects in React JS?

Here’s my code:

    const columns = [
    { field: 'id', headerName: 'ID', width: 200 },
    { field: 'season', headerName: 'Season', width: 200 },
    { field: 'transferWindow', headerName: 'Transfer Window', width: 200 }
]
<table>
                <thead>
                    <tr>
                        {columns.map((item) => {
                            <th key={item.field}>{item.field}</th>
                        })}
                        
                        {/* <th>{columns[0].field}</th>
                        <th>{columns[1].field}</th>
                        <th>{columns[2].field}</th> */}
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td></td>
                    </tr>
                </tbody>
            </table>

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.

export default function App() {
  const columns = [
    { field: "id", headerName: "ID", width: 200 },
    { field: "season", headerName: "Season", width: 200 },
    { field: "transferWindow", headerName: "Transfer Window", width: 200 }
  ];
  return (
    <div className="App">
      <table>
        <thead>
          <tr>
            {columns.map((item) => (
              <th key={item.field}>{item.field}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          <tr>
            <td></td>
          </tr>
        </tbody>
      </table>
    </div>
  );
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement