chris loughnane
chris loughnane

Reputation: 2748

How can I render the contents of an array of arrays in React?

I am really surprised I even have to ask this question but I am completely stumped. In Angular I use nested *ngFor but in React I can't figure out how to render a 2d array that's fetched from an API. I have no problem with rendering a flat array. (example below)

The 2D array is to generate separate rows of icons. Perhaps I could use a filter with the row property on each of the icon objects; I would really like to know how to traverse a 2D array.

snipets React works with flat array

{this.state.icons.map((icon) => (
  <li className="icons">
    {icon.type === 'icon' && (
      <a href={icon.targetUri} target="_blank">
          <img
            className="large-icon"
            src={icon.image} />
      </a>
    )}
  </li>
))}

Angular 9

 <div class="col-12">
      <ul       
        runInsideAngular="false"
        *ngFor="let row of rows; let i = index;">
        <li 
          class="icons"
          *ngFor="let icon of row"
...

enter image description here

Upvotes: 0

Views: 763

Answers (1)

Prateek Thapa
Prateek Thapa

Reputation: 4938

You could simply nest .map() calls

Here is a working example :- https://stackblitz.com/edit/react-t2hrra

const arrOfArray = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
]

function App() {
  return (
    <div>
      {arrOfArray.map(arr => {
        return arr.map(a => {
          return <p>{a}</p>
        })
      })}
    </div>
  );
}

Upvotes: 1

Related Questions