Start your developer blog today!
Email me

How to Render Elements Using JSX and Loops in React

Aug 22, 2020 1 min read

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 (
      {dogBreeds.map((value, index) => {
        return <li key={index}>{value}</li>

More JavaScript Articles