Offswitch
Offswitch

Reputation: 71

Multi-line for loop in JSX

I'm totally new to JSX and am having a difficult time trying to figure out how to write multiple lines of JSX (a for-in loop in this case). Does the entire need to be wrapped in the arrow function?

The error I see from Babeljs.io is:

/repl.jsx: Unexpected token (37:5)

  35 |
  36 |   return (
> 37 |     {( () => {
     |      ^

import ExpenseItem from "./components/ExpenseItem";

function App() {
  const expenses = [
    {
      id: "e1",
      title: "Toilet Paper",
      amount: 94.12,
      date: new Date(2020, 7, 14),
    }
  ];

  return (
    <div>
      {( () => {
        for (expense in expenses) {
          <ExpenseItem
            title={expense.title},
            amount={expense.amount},
            date={expense.date}
          ></ExpenseItem>;
        }
      })()}      
    </div>
  );
}

Upvotes: 0

Views: 178

Answers (1)

Rob Bailey
Rob Bailey

Reputation: 981

You should use expenses.map e.g.

    <div>
      { 
        expenses.map((expense) => (
          <ExpenseItem
            title={expense.title}
            amount={expense.amount}
            date={expense.date}
          ></ExpenseItem>
        ))
      }      
    </div>

Upvotes: 1

Related Questions