1

I am building a multilevel menu and want to use recursion to display the menu. Something like the multi-level dropdown from here.

In my code my menu looks like this.

const menu = [
  {
    name: 'Man Utd',
    menu: [
       {
          name: 'Stadium'
       },
       {
          name: 'About'
       }
    ]
  },
  {
    name: 'Liverpool',
    menu: [
       {
           name: 'Contact'
       }
    ]
  }
];

which I then pass this into my react component.

const Dropdown = ({ menu }) => {
    const renderMenu = (items) => {
        return items.map((item: any, index: any) => {
            return (
                <div>
                    {item.menu ? renderMenu() : item.name}
                </div>
            )
        })
    }

    return (renderMenu(menu));
}

the issue here is that it is causing an infinite loop.

Can anyone advise me as to how I can improve this?

2 Answers 2

2

You need to pass item.menu as argument to renderMenu when you recursively render the menu.

Example

const menu = [
  {
    name: "Man Utd",
    menu: [
      {
        name: "Stadium"
      },
      {
        name: "About"
      }
    ]
  },
  {
    name: "Liverpool",
    menu: [
      {
        name: "Contact"
      }
    ]
  }
];

const Dropdown = ({ menu }) => {
  const renderMenu = items => {
    return items.map((item: any, index: any) => {
      return (
        <div style={{ marginLeft: 10 }}>
          {item.name}
          {item.menu ? renderMenu(item.menu) : null}
        </div>
      );
    });
  };

  return <div>{renderMenu(menu)}</div>;
};

ReactDOM.render(<Dropdown menu={menu} />, 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>

Sign up to request clarification or add additional context in comments.

7 Comments

this is great, thanks. Any idea of the best way to hide the secondary menu. and only show on hover?
@peterflanagan You're welcome! That complicates it a bit, but you might be able to implement that purely in CSS.
ah, ok, maybe something easier that I can't figure out. How can I make the secondary menus and any menu below display: none? ` - index > 0 doesn't work as it just does the first menu? Any ideas? Thanks again
@peterflanagan Please don't change the question after it has been answered. Consider creating a new question entirely if you can't figure it out.
will do makes sense!
|
1

Your not passing down anything to renderMenu. You should call renderMenu(item.menu)

Comments

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.