Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering a nested navigation in React

I have the following data structure for my website’s navigation. This is just a JSON object:

[{
  "path": "/",
  "name": "Home"
}, {
  "path": "/products",
  "name": "Products",
  "subnav": [{
    "path": "/sharing-economy",
    "name": "Sharing Economy"
  }, {
    "path": "/pre-employment-screening",
    "name": "Pre-Employment Screening"
  }, {
    "path": "/kyc-and-aml",
    "name": "KYC & AML"
  }]
}, {
  "path": "/checks",
  "name": "Checks"
}, {
  "path": "/company",
  "name": "Company"
}]

What I’d like to do is to render the following from it, having a nested list inside of the Products list item when the subnav key is present:

<ul>
  <li>Home</li>
  <li>Products
    <ul>
      <li>Sharing Economy</li>
      <li>Pre-Employment Screening</li>
      <li>KYC & AML</li>
    </ul>
  </li>
  <li>Checks</li>
  <li>Company</li>
</ul>

Currently, my React code looks like this:

// This is the data structure from above
import navigation from '../data/navigation.json'

const SubNavigation = (props) => {
  // Here I’m trying to return if the props are not present
  if(!props.subnav) return
  props.items.map((item, index) => {
    return <Link key={index} to={item.path}>{item.name}</Link>
  })
}

class Header extends React.Component {

  render() {
    return (
      <header className='header'>
        {navigation.map((item, index) => {
          return(
            <li key={index}>
              <Link to={item.path}>{item.name}</Link>
              <SubNavigation items={item.subnav}/>
            </li>
          )
        })}
      </header>
    )
  }
}

export default Header

I’m using a functional stateless component to render the SubNavigation, however am running into trouble when item.subnav is undefined.

How would I adapt this code so that I conditionally render the SubNavigation based on the item.subnav key being present/undefined.

like image 741
gosseti Avatar asked Mar 03 '26 13:03

gosseti


1 Answers

Could you try this:

  <header className='header'>
    {navigation.map((item, index) => {
      return(
        <li key={index}>
          <Link to={item.path}>{item.name}</Link>
          { item.subnav && <SubNavigation items={item.subnav}/> }
        </li>
      )
    })}
  </header>
like image 188
David Guan Avatar answered Mar 06 '26 03:03

David Guan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!