乐闻世界logo
搜索文章和话题

How to have nested loops with map in JSX?

1个答案

1

In JSX, you can use .map() or other iteration methods to nest loops within JSX elements. See the following example, which demonstrates how to use nested loops to render data from a multidimensional array.

jsx
function NestedLoopsComponent({ multiDimensionalArray }) { return ( <div> {multiDimensionalArray.map((subArray, index) => ( <div key={index}> {subArray.map((item, itemIndex) => ( <span key={itemIndex}>{item}</span> ))} </div> ))} </div> ); }

In this example, multiDimensionalArray is an array where each element is also an array. We first iterate over the outer array, and for each iteration of the outer array, we iterate over the inner array. Each element of the inner array is wrapped in a <span> tag, and each inner array as a whole is wrapped in a <div> tag.

Please note that all elements created within the .map() method must have a unique key attribute, which helps React identify changes, additions, or removals of items. In this example, I used the array index as the key, but in real-world applications, you should use a more stable and unique identifier as the key.

2024年6月29日 12:07 回复

你的答案