How to render nested array elements in React?
Asked Answered
P

1

8

I want to render nested array elements. To render elements I used .map but it is not working for second array.

Using list=[{value: 'One', list:[{value: 'abc', selected: false}, {value: 'efg', selected: false}]}, {value: 'Two', list: [{value: 'psr', selected: false}]}];

   list.map((item, index) => {
        return (
          <div key={index}>
            <ul >{item.value}</ul>
            item.list.map((subitem, i) => {
              return (
                 <ul >{subitem.value}</ul>
              )
            })
          </div>
        )
      })

Am I missing anything here?

Thanks

Prose answered 3/5, 2017 at 9:34 Comment(5)
Do you want to render them in nested lists, or flatten the array?Exertion
@TomFenech I have to show nested array detailsProse
I can see your array, what you need to show us is the desired structure of the HTML that you are trying to produce. At the moment, what you have is invalid.Exertion
@TomFenech yes. I don't know how to use .map for nested arrayProse
jsfiddle.net/jwm6k66c/2611 Check this.Demagoguery
D
30

Try this. You missed { } before your second map

 list.map((item, index) => {
            return (
              <div key={index}>
                <ul >{item.value}</ul>
               {
                item.list.map((subitem, i) => {
                  return (
                     <ul ><li>{subitem.value}</li></ul>
                  )
                })
               }
              </div>
            )
          }

DEMO: https://jsfiddle.net/jwm6k66c/2611/

Demagoguery answered 3/5, 2017 at 9:39 Comment(9)
Try adding an explanation to your answer!Exertion
@TomFenech I was in middle of addingDemagoguery
Your answer deals with a possible syntax error but fails to take into account the fact that a text node is not a permitted child of a <ul> element.Exertion
Throws error. It says Cannot read property 'map' of undefined. Referd item.list.mapProse
Okat. Thanks @DemagogueryProse
@AnushaNilapu Welcome .Demagoguery
@Demagoguery Still getting same error. I can see item.list has array but it fails.Prose
Let us continue this discussion in chat.Prose
Last line should be }), in the jsfiddle it is correctIndemnify

© 2022 - 2024 — McMap. All rights reserved.