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.

5
  • 1
    You aren't returning anything in your map call. {columns.map((item) => { return <th key={item.field}>{item.field}</th>})} see: When should I use a return statement in ES6 arrow functions Commented Jan 22, 2022 at 2:32
  • 1
    Does this answer your question? When should I use a return statement in ES6 arrow functions Commented Jan 22, 2022 at 2:35
  • 1
    I would just make a little function to create each <th> element on its own and insert it in between the open and closing head <tr> tags. Something like <tr><Headings /><tr> Commented Jan 22, 2022 at 2: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). Commented Jan 22, 2022 at 2:38
  • 1
    Try replacing: {columns.map((item) => { <th key={item.field}>{item.field}</th> })} with {columns.map(item => ( <th key={item.field}>{item.field}</th> ))} Commented Jan 22, 2022 at 3:49

1 Answer 1

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>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.