in React JS by

How to loop inside JSX?

1 Answer

0 votes
by

You can simply use Array.prototype.map with ES6 arrow function syntax. For example, the items array of objects is mapped into an array of components:

<tbody>
  {items.map(item => <SomeComponent key={item.id} name={item.name} />)}
</tbody>

You can't iterate using for loop:

<tbody>
  for (let i = 0; i < items.length; i++) {
    <SomeComponent key={items[i].id} name={items[i].name} />
  }
</tbody>

This is because JSX tags are transpiled into function calls, and you can't use statements inside expressions. This may change thanks to do expressions which are stage 1 proposal.

Related questions

0 votes
asked Feb 14 in React JS by Robindeniel
0 votes
0 votes
asked Nov 26, 2019 in React JS by AdilsonLima
0 votes
asked Nov 26, 2019 in React JS by AdilsonLima
0 votes
asked Jul 2, 2019 in React JS by Venkatshastri
0 votes
asked Mar 1, 2020 in C Plus Plus by SakshiSharma
0 votes
asked Jan 9, 2020 in Vue.JS by GeorgeBell
...