Skip to content

How to loop inside React JSX

New Course Coming Soon:

Get Really Good at Git

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>
)
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my React Beginner's Handbook
→ Read my full React Tutorial on The Valley of Code

Here is how can I help you: