AI Workshop: learn to build apps with AI →
JSX Recipes: How to loop inside React JSX

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Suppose you have a React component and an items array you want to loop over, to print all the “items” you have.

Here’s how you can do it.

In the returned JSX, add a <ul> tag to create a list of items:

return (
  <ul>

  </ul>
)

Inside this list, we add a JavaScript snippet using curly brackets {} and inside it we call items.map() to iterate over the items.

We pass to the map() method a callback function that is called for every item of the list.

Inside this function we return a <li> (list item) with the value contained in the array, and with a key prop that is set to the index of the item in the array. This is needed by React.

return (
  <ul>
    {items.map((value, index) => {
      return <li key={index}>{value}</li>
    })}
  </ul>
)

You can also use the shorthand form with implicit return:

return (
  <ul>
    {items.map((value, index) => <li key={index}>{value}</li>}
  </ul>
)

Lessons in this unit:

0: Introduction
1: How to render HTML in React
2: Conditional rendering in React
3: ▶︎ How to loop inside React JSX
4: React, how to make responsive JSX
5: How to repeat displaying something in JSX
6: How to move around blocks of code with React and Tailwind