Using a map within a map in jsx

Viewed 25783
{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.

4 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!

Related