How to loop JSX in React

React 2 min read

The are certain ways how you can loop JSX in React. The most popular and yet simple way is to use map() method.

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

Let’s imagine we have a simple application where we have a list with programming languages. We call render them one by one by one by calling <ListItem> and passing language as a prop.

import React from "react";

const List = ({ children }) => <ul>{children}</ul>;

const ListItem = ({ language }) => <li>{language}</li>;

const App = () => (
  <List>
    <ListItem language="JavaScript" />
    <ListItem language="Java" />
    <ListItem language="TypeScript" />
  </List>
);

export default App;

In our case, we have only 3 languages we need to render, but what you would need to do if the requirement was to render the dynamic data which was coming from the API? In that situation, the first thing you would obviously do is start to update the component logic. There are several solutions to this problem.

Solution

One of the options is just simply map through an array of elements directly in JSX.

import React from "react";

const languages = ["JavaScript", "Java", "TypeScript"];

const List = ({ children }) => <ul>{children}</ul>;

const ListItem = ({ language }) => <li>{language}</li>;

const App = () => (
  <List>
    {languages.map((language, index) => (
      <ListItem key={index} language={language} />
    ))}
  </List>
);

export default App;

Another solution is very similar to the first one and the real difference is that we move the looping logic out of the JSX and create a new listItems variable instead.

import React from "react";

const languages = ["JavaScript", "Java", "TypeScript"];

const List = ({ children }) => <ul>{children}</ul>;

const ListItem = ({ language }) => <li>{language}</li>;

const listItems = languages.map((language, index) => (
  <ListItem key={index} language={language} />
));

const App = () => <List>{listItems}</List>;

export default App;

About me

My name is Edvins Antonovs, and I am a Developer, Designer and Entrepreneur. I'm passionated about the Front-End and JavaScript. I enjoy sharing my knowledge with the others.