0

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.

lastone
  • 99
  • 1
  • 8
  • 1
    You aren't returning anything in your map call. `{columns.map((item) => { return {item.field}})}` see: [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions) – pilchard Jan 22 '22 at 02:32
  • 1
    Does this answer your question? [When should I use a return statement in ES6 arrow functions](https://stackoverflow.com/questions/28889450/when-should-i-use-a-return-statement-in-es6-arrow-functions) – pilchard Jan 22 '22 at 02:35
  • 1
    I would just make a little function to create each element on its own and insert it in between the open and closing head tags. Something like – Chris Jan 22 '22 at 02:37
  • 1
    @Chris regardless, it is better that the OP understand the syntax mistake at play here (lest it be repeated in the proposed Headings component). – pilchard Jan 22 '22 at 02:38
  • 1
    Try replacing: `{columns.map((item) => { {item.field} })}` with `{columns.map(item => ( {item.field} ))}` – jsN00b Jan 22 '22 at 03:49

1 Answers1

1

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>
  );
}
Anil
  • 196
  • 1
  • 3