Using the Map Function
The map function loops over the items of a given array and returns the specified statement or code for each.
For a flat array, the map function works as follows:
In React, you must wrap the map function with curly brackets and use an arrow function to return a node element for each iteration. The items in the flat array above can be rendered as JSX elements like this:
Note that you assign a key to each element the map function returns. This helps React identify items that have been changed or removed. This is important during the reconciliation process.
Mapping Over a Nested Array in a React Component
A nested array is similar to an array that contains another array. For example, the following recipe array contains an object with an array.
For data like this with nested arrays, you should use a map function for each array.
In this example, you would map over the data array as shown below:
The Recipes component will render the div element containing the recipe data for each recipe in the recipes array.
Working With Arrays in JavaScript
JavaScript offers a wide variety of array methods that make working with arrays simpler. This article demonstrated how to render data from a nested array using a map array method. Apart from map, there are also methods to help you push data to an array, concatenate two arrays, or even sort an array.