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?
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>
Your not passing down anything to renderMenu. You should call renderMenu(item.menu)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.