0

In my React project, I'm passing in an array of objects and wondering how I can set default parameter for the nested array. I've already set it on the main array const Nav = ({ navItems = [] }) but couldn't figure out how to set for nested array. Logically, I tried const Nav = ({ navItems = [], navItems.subMenu = [] }) however seems like syntax is incorrect.

JSX:


const Nav = ({ navItems = [] }) => {

const subItems = navItems.map(el => el.subMenu)

return (
  {navItems.map(item => (
    <li>
      <a href="#">{item.label}</a>
      <ul>
        {subItems[0].map(subItem => (
            <li>{subItem.item}</li>
        ))}
      </ul>
    </li>
  ))}
)

}

Props getting passed in:

<Nav
        navItems={[
          {
            label: "About",
            subMenu: [
              {
                id: 1,
                item: "About Sub Item 1",
              },
              {
                id: 2,
                item: "About Sub Item 2",
              },
              {
                id: 3,
                item: "About Sub Item 3",
              },
            ],
          },
          {
            label: "Blog",
            subMenu: [
              {
                id: 1,
                item: "Blog Sub Item 1",
              },
              {
                id: 2,
                item: "Blog Sub Item 2",
              },
              {
                id: 3,
                item: "Blog Sub Item 3",
              },
            ],
          },
        ]}
      />
Eric Nguyen
  • 926
  • 3
  • 15
  • 37

2 Answers2

1

Here you go :

const Nav = ({ navItems = [{subMenu : []}] })

// I think you also need to set for label also, else will throw error while render
const Nav = ({ navItems = [{ label: "Default label" ,subMenu : []}] })

Suggestion , you can change the code block to something like this :

const Nav = ({ navItems = [] }) => {
  // there is no need of below line
  // const subItems = navItems.map(el => el.subMenu)  

  return (
    {navItems.map((item) => (
      <li>
        <a href="#">{item.label}</a>
        <ul>
          {item.subMenu.map(subItem => ( //<---- you can use it like this
              <li>{subItem.item}</li>
          ))}
        </ul>
      </li>
    ))}
  ) 
}
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
0

I think the issue might be that it can't deconstruct the array you're passing. If you do ({obj}), it's being deconstructed and it accesses its properties. If it can't be deconstructed, it fires up an error. It should work like this

const Nav = ( navItems = [] ) => {

const subItems = navItems.map(el => el.subMenu)

return (
  {navItems.map(item => (
    <li>
      <a href="#">{item.label}</a>
      <ul>
        {subItems[0].map(subItem => (
            <li>{subItem.item}</li>
        ))}
      </ul>
    </li>
  ))}
)

}
Elisabetta
  • 81
  • 7