Use a map() inside a map() function in React

avatar

Borislav Hadzhiev

Fri Apr 22 20222 min read

banner

Photo by Luke Moss

Use a map() inside a map() function in React #

To use a map() inside a map() function in React:

  1. Call map() on the outer array, passing it a function.
  2. On each iteration, call the map() method on the other array.
App.js
export default function App() { const employees = [ {id: 1, name: 'Alice', tasks: ['dev', 'test', 'ship']}, {id: 2, name: 'Bob', tasks: ['design', 'test']}, {id: 3, name: 'Carl', tasks: ['test']}, ]; return ( <div> {employees.map((employee, index) => { return ( <div key={index}> <h2>Name: {employee.name}</h2> {employee.tasks.map((task, index) => { return ( <div key={index}> <h2>Task: {task}</h2> </div> ); })} <hr /> </div> ); })} </div> ); }

The function we passed to the Array.map method gets called with each element in the array and the index of the current iteration.

On each iteration, we render the name property of the employee object and use a nested map() to iterate over the tasks array of each employee.

Notice that when calling the map() method inside of our JSX code, we have to use curly braces {} to wrap the call to map().

This is needed only in your JSX code and signals to React that we are writing an expression that has to get evaluated.

We used arrow functions with explicit return statements in both calls to the map() method. If you only need to render some JSX elements and don't use conditions, declare variables, etc, you can use an implicit return, which would make your code a little more readable.

App.js
export default function App() { const employees = [ {id: 1, name: 'Alice', tasks: ['dev', 'test', 'ship']}, {id: 2, name: 'Bob', tasks: ['design', 'test']}, {id: 3, name: 'Carl', tasks: ['test']}, ]; return ( <div> {employees.map((employee, index) => ( <div key={index}> <h2>Name: {employee.name}</h2> {employee.tasks.map((task, index) => ( <div key={index}> <h2>Task: {task}</h2> </div> ))} <hr /> </div> ))} </div> ); }

We used implicit returns for both of the arrow functions we passed to the map() method.

App.js
const arr = ['a', 'b', 'c']; // 👇️ explicit return const result1 = arr.map(element => { return element; }); // 👇️ implicit return const result2 = arr.map(element => element);

You can only use implicit returns when you don't have to use conditionals or define variables in the function you pass to map().

We used the index for the key prop in the examples, however it's better to use a stable unique identifier if you have one. We could have used the id property on each object.

The key prop is used internally by React for performance reasons. It helps the library make sure to only re-render the array elements that have changed.

Having said that, you won't see any noticeable difference unless you're dealing with many thousands of array elements.

Use the search field on my Home Page to filter through my more than 1,000 articles.