V
V
Vladimir2020-02-13 17:24:40
JavaScript
Vladimir, 2020-02-13 17:24:40

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>


Now I am sorting the menu in order and displaying the titles of the items in the console, how can I implement this? Thank you.

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

1 answer(s)
0
0xD34F, 2020-02-13
@HistoryART

const Menu = ({ items }) =>
  items instanceof Array && items.length
    ? <ul>
        {items.map(n => (
          <li key={n.id}>
            <a>{n.title}</a>
            <Menu items={n.children} />
          </li>
        ))}
      </ul>
    : null;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question