Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a map within a map in jsx

{normalizedData.map(obj => 
    <div key={obj.display_date_numberic}>
        <div>{obj.display_date_numberic}</div>
    </div>

    {!isEmpty(obj.applicants) && obj.map(obj2 => 
        <div className="events">{obj2.person.name}</div>
    )}
)}

I'm getting an error on the following line:

{!isEmpty(obj.applicants) && obj.map(obj2 =>

Why can't I use the map function inside another map? normalizedData has an array of objects and each obj has another array of objects.

like image 809
Giala Jefferson Avatar asked May 23 '17 09:05

Giala Jefferson


People also ask

Can we use map inside a map in react JS?

Use a map() inside a map() function in React # To use a map() inside a map() function in React: Call map() on the outer array, passing it a function. On each iteration, call the map() method on the other array.

How do you call a map in React?

In React, the map method is used to traverse and display a list of similar objects of a component. A map is not a feature of React. Instead, it is the standard JavaScript function that could be called on an array. The map() method creates a new array by calling a provided function on every element in the calling array.


1 Answers

You can do a map within a map as follows:

e.g. given data of

outerArray: [
  { id: '1st', innerArray: [ 'this', 'that' ]},
  { id: '2nd', innerArray: [ 'some', 'what' ]},
]

you can use JSX:

<ul>
  {outerArray.map(outerElement => {
    return outerElement.innerArray.map(innerElement => (
      <li key={outerElement.id}>
        {innerElement} - {outerElement.id}
      </li>
    ))
  })}
</ul>

or slightly more succinctly:

<ul>
  {outerArray.map(outerElement => (
    outerElement.innerArray.map(innerElement => (
      <li key={outerElement.id}>
        {innerElement} - {outerElement.id}
      </li>
    ))
  ))}
</ul>

which renders:

<ul>
<li>this - 1st</li>
<li>that - 1st</li>
<li>some - 2nd</li>
<li>what - 2nd</li>
</ul>

note the use of key= inside the map to ensure React has a unique reference for the element from each loop iteration. If you don't it will warn you!

like image 124
Andy Lorenz Avatar answered Sep 19 '22 22:09

Andy Lorenz