Bootcamp
Search…
7.1.2: Rendering in a Loop

Introduction

React strongly urges the use of the map function to create elements in a loop. map takes an array as input, runs a function to transform each element (without altering the original array), and returns a new array with the transformed elements.
The following code snippets are examples for illustration and we do not need to use them in our app.

Basic map Example

1
const array1 = [1, 4, 9, 16];
2
​
3
// pass a function to map
4
const array2 = array1.map((x) => x * 2);
5
​
6
console.log(array2);
7
// expected output: Array [2, 8, 18, 32]
Copied!

Using map in JSX Example

In this case we are taking an array of data and creating an array of React elements.
1
const numbers = [1, 2, 3, 4, 5];
2
const jsxListItems = numbers.map((number) => <li>{number}</li>);
3
console.log(jsxListItems);
Copied!

Missing Keys

Running the above example, will cause React to print a warning to our console our elements don't have unique 'key' attributes. React depends on HTML element keys to re-render list elements efficiently and thus sends this alert.
Below is an example of adding this attribute.
1
const numbers = [1, 2, 3, 4, 5];
2
const listItems = numbers.map((number) => (
3
<li key={number.toString()}>{number}</li>
4
));
Copied!
*Note that keys MUST be unique. The example above is simple. Essentially when you plan your project, ensure that you can have a unique id for each iteration of any array of data that you will be mapping from your array!*

Putting it All Together

We can create an array of JSX elements with map and directly mention the array in the JSX, as seen below with {jsxListItems}.
The following code snippet is an example we can copy into the Webpack MVC Base repo to play with.
src/index.jsx
1
import React from 'react';
2
import { render } from 'react-dom';
3
​
4
// Create an array of HTML list elements from an array of numbers
5
const numbers = [1, 2, 3, 4, 5];
6
const jsxListItems = numbers.map((number) => (
7
<li key={number.toString()}>{number}</li>
8
));
9
console.log(jsxListItems);
10
​
11
// Create a JSX element that uses the array of HTML list elements
12
const myEl = (
13
<div>
14
<h1 className="hero-text">
15
Hey <span className="warning">Wow!</span>
16
</h1>
17
<ul>{jsxListItems}</ul>
18
</div>
19
);
20
// Log the JSX element to verify its contents
21
console.log('myEl:', myEl);
22
​
23
// Create an element that React will render elements into
24
const rootElement = document.createElement('div');
25
// Append root element to page
26
document.body.appendChild(rootElement);
27
// Have React render the JSX element into the root element
28
render(myEl, rootElement);
Copied!