Blog.

How to loop in React's JSX

Cover Image for How to loop in React's JSX

The easiest way to loop over an array in React JSX is by using the native map function

 

The easiest way to loop over an array in React JSX is by using the native map function:

const users = [
  {
    id: 1,
    name: 'John Doe',
  },
  {
    id: 2,
    name: 'Jack Rolsten',
  },
]
function UsersList() {
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  )
}

Note: You might have noticed that each <li> element contains a key prop. Keys help React identify which items have changed, are added, or are removed. Keys should be given to the elements inside the array to give the elements a stable identity:

Create a JSX fragment with a for each loop

function FruitsList(props) {
  const fruits = [🍎,🍌,🥭,🍐];
  const listOfFruits = [];
  fruits.forEach((fruit, index) => {
    listOfFruits.push(<li key={index}>{fruit}</li>)
  })
  return (
    <ul>
      {listOfFruits}
    </ul>
  )
}

Daniel Turuș

@danielturus

Hi! My name is Daniel and I am a Full-stack JavaScript developer.

If you like my material, please consider following me on Twitter to get notified when new posts are published, ask me a question and stay in touch.