Answer the question
In order to leave comments, you need to log in
How to build a nested menu?
Good afternoon. Tell me please. I'm rewriting a react project, if I try with createElem/appendChild I get an error. I need to return a menu in this format:
<nav>
<ul>
<li>
<ul>
<li><Link to='/'>Children item</Link></li>
</ul>
<Link to='/'>Item</Link>
</li>
</ul>
</nav>
export default function TopBar() {
return (
<Router>
{ createNavigation(navigationItems) }
</Router>
)
}
const navigationItems = [
{
id: 3,
title: 'Пункт 3',
children: [
{
id: 1,
title: 'Пункт 1'
}
]
},
{
id: 2,
title: 'Пункт 2',
children: [
{
id: 1,
title: 'Пункт 1'
}
]
},
{
id: 1,
title: 'Пункт 1',
children: [
{
id: 1,
title: 'Пункт 1'
}
]
},
{
id: 4,
title: 'Пункт 4',
children: [
{
id: 1,
title: 'Пункт 1'
},
{
id: 3,
title: 'Пункт 3'
},
{
id: 2,
title: 'Пункт 2'
}
]
}
];
function sortItemsInOrder(items) {
if(Array.isArray(items)) {
items = items.sort(inOrder);
function inOrder(item1, item2) {
return item1.id - item2.id
}
return items
}
return [{id: 0, title: 'No items', children: [{id: 0, title: 'No children items'}]}]
}
function createNavigation(items) {
sortItemsInOrder(items).forEach((item, i, arr) => {
console.log(item.title);
sortItemsInOrder(item.children).forEach((item, i, arr) => {
console.log(item.title)
})
});
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question