Skip to content

How to loop inside React JSX

How to do a loop in a React component

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>
)

→ Get my React Beginner's Handbook

→ I wrote 17 books to help you become a better developer:

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook
...download them all now!

Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list