0

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

2
  • 1
    I pretty sure you can just nest map() calls. Commented Sep 13, 2020 at 3:30
  • I was pretty sure too but I couldn't get it to render. I'll try again in the morning. Commented Sep 13, 2020 at 3:33

1 Answer 1

1

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>
  );
}

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, your snippet proved to me I am doing it the correct way with nested map. There's something wrong in my data although it looks perfectly fine when inspected with chrome components extension. BTW the link isn't working correctly.
I hardcoded an example of my data and it works perfectly with nested map. So something is failing when I fetch the data, I now think the two dimensional array is not ready by the time the render is fired.
Thanks for that. I thought I was going mad. I'm an Angular dev testing out React and I like what I see so far. I just need to figure out why my data is bad in the app but hardcoded it's fine. stackblitz.com/edit/react-nested-map-2d-array?file=src/App.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.