Home > Blockchain >  How to Render Nested Map Items inside react component
How to Render Nested Map Items inside react component

Time:02-20

I have a react navigation component that is rendered based on some JSON data.

I have sucessfully rendered the top level items, but I'm having trouble rendering the second level sub pages.

This is how I think the code should look I also only want the

    tag to be output can someone help me with the syntax to achive this?

        {headerData.TopLevelPages.map(toplevelPage => (
            <li key={toplevelPage.Id}>{toplevelPage.NavLinkText}</li>
        
             <ul>//Only out put UL If SubNavMenuItems as items
        
                {toplevelPage.SubNavMenuItems.map(sublevelPage => (
                       <li key={sublevelPage.Id}>{sublevelPage.NavLinkText}</li>
                     ))}
        
            <ul>
    
       ))}
    

    CodePudding user response:

    A simple recursive function can render a nested menu with any depth.

    Try like below.

    const headerData = { TopLevelPages: [ { NavLinkText: "Text 1", Id: "1", SubNavMenuItems: [ { NavLinkText: "sub Text 1-1", Id: "1-1" }, { NavLinkText: "sub Text 1-2", Id: "1-2", SubNavMenuItems: [ { NavLinkText: "sub-sub Text 1-2-1", Id: "1-2-1" } ] } ] }, { NavLinkText: "Text 2", Id: "2" } ] };
    
    function App() {
      
      const renderNavMenu = (menus) => {
        return menus.map(({ NavLinkText, Id, SubNavMenuItems }) => (
          <ul>
            {/* render current menu item */}
            <li key={Id}>{NavLinkText}</li>
            {/* render the sub menu items */}
            {SubNavMenuItems && <ul>{renderNavMenu(SubNavMenuItems)}</ul>}
          </ul>
        ));
      };
    
      return renderNavMenu(headerData.TopLevelPages);
    }
    
    ReactDOM.render(<App/>, document.getElementById("root"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root"></div>

    CodePudding user response:

        {headerData.TopLevelPages.map(toplevelPage => (
            <li key={toplevelPage.Id}>{toplevelPage.NavLinkText}</li>
        
        { toplevelPage.SubNavMenuItems && 
            ( <ul>//Only out put UL If SubNavMenuItems as items
        
                {toplevelPage.SubNavMenuItems.map(sublevelPage => (
                       <li key={sublevelPage.Id}>{sublevelPage.NavLinkText}</li>
                     ))}
        
            <ul>)
        }
    
       ))}
    

    do a conditional rendering once more

    • Related