0

Hey guys Im trying to make a menu that renders the menu items from this json data.

Im doing this using react so just trying to get the correct syntax around it, here is the data,

 {
        "name": "menu",
        "children": [
          {
            "title": "Account",
            "children": [
              {
                "name": "Preferences"
              },
              {
                "name": "Contact Details"
              },
              {
                "name": "Manage Users"
              }
            ]
          },
          

          {
            "title": "Design",
            "children": [
              {
                "name": "Themes"
              },
              {
                "name": "Gallery"
              },
              {
                "name": "Templates"
              }
            ]
          },

currently I'm mapping over it and can only get access to the title,

 {menu.map((item, i) => (
        <div key={i}>
          <h2>{item.title}</h2>
        </div>
      ))}
    </div>

whats the correct way to get access to the children array within the data so I can then render out the items with an onclick or something ?

cheers

1
  • You need to loop on menu.children. Please check the answer. Commented May 27, 2021 at 5:47

3 Answers 3

2

You will need to use another .map function within to map through the children.

{menu.map((item, i) => (
  <div key={i}>
    <h2>{item.title}</h2>
    {item.children.map((item, i) => (
      <h4>{item}</h4>
    ))}
  </div>
))}
Sign up to request clarification or add additional context in comments.

Comments

0

you can simply call the children inside the map, for the example

{menu.map((item, i) => (
        <div key={i}>
          <h2>{item.title}</h2>
          {item.children.map(child => <p>{child.name}</p>}
        </div>
      ))}
    </div>

Comments

0

here is your updated code

{menu.children.map((item, i) => (
    <div key={i}>
      <h2>{item.title}</h2>
     {item.children.map((item, i) => (
       <h4>{item.name}</h4>
     ))}
    </div>
  ))}
</div>}

https://codesandbox.io/s/modest-dust-po682?file=/src/App.js

4 Comments

still receiving. Cannot read property 'map' of undefined
ok yes I understand that and have access to the title, but then how do you get access to the "name" sub categories in the children array within it? thanks I will then give you the answer
@JamesWuhan Hey James, Please mark the answer and vote up. Thanks.

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.