How to Render Elements Using JSX and Loops in React

Published Aug 22, 2020

Suppose we want to render out a list of dogs (as one does) dynamically in a React component using JSX.

One option is to render each JSX element and place them in an array.

const DogList = () => {
  const dogBreeds = ['corgi', 'shih tzu', 'pug'];
  const dogs = [];
  for(const [index, value] of dogBreeds.entries()) {
    dogs.push(<li key={index}>{value}</li>)   
  }
  return <ul>{dogs}</ul>;
}

Another option is to use map() in our JSX to avoid the for-of loop.

const DogList = () => {
  const dogBreeds = ['corgi', 'shih tzu', 'pug'];
  return (
    <ul>
      {dogBreeds.map((value, index) => {
        return <li key={index}>{value}</li>
      })}
    </ul>
  )
}

More JS Articles