Skip to content

Edvins Antonovs

How to loop in JSX

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

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 to list programming languages. We call render on them one by one by calling <ListItem> and passing language as a prop.

1import React from 'react';
2
3const List = ({ children }) => <ul>{children}</ul>;
4
5const ListItem = ({ language }) => <li>{language}</li>;
6
7const App = () => (
8 <List>
9 <ListItem language="JavaScript" />
10 <ListItem language="Java" />
11 <ListItem language="TypeScript" />
12 </List>
13);
14
15export default App;

In our case we have only 3 languages we need to render, but what would we need to do if the requirement was to render dynamic data which was coming from an API? Current approach would be insufficient, so we would need to update the component logic. There are several solutions to this problem.

Solution

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

1import React from 'react';
2
3const languages = ['JavaScript', 'Java', 'TypeScript'];
4
5const List = ({ children }) => <ul>{children}</ul>;
6
7const ListItem = ({ language }) => <li>{language}</li>;
8
9const App = () => (
10 <List>
11 {languages.map((language, index) => (
12 <ListItem key={index} language={language} />
13 ))}
14 </List>
15);
16
17export 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.

1import React from 'react';
2
3const languages = ['JavaScript', 'Java', 'TypeScript'];
4
5const List = ({ children }) => <ul>{children}</ul>;
6
7const ListItem = ({ language }) => <li>{language}</li>;
8
9const listItems = languages.map((language, index) => <ListItem key={index} language={language} />);
10
11const App = () => <List>{listItems}</List>;
12
13export default App;
© 2024 by Edvins Antonovs. All rights reserved.