DuckQueen
DuckQueen

Reputation: 802

How to create a nested menu in JavaScript?

So I want to achieve the image below but with content sent from server.

enter image description here

We can set menu items

const items = [
  { key: 'editorials', active: true, name: 'Editorials' },
  { key: 'review', name: 'Reviews' },
  { key: 'events', name: 'Upcoming Events' },
]
//...
    <Menu vertical color='black' items={items}>

    </Menu>

However, I do not see how to nest them. Just setting item 'content' to some XML.

How do I create a menu with multiple nested sections in ReactJS\Semantic-UI in Javacript?

Upvotes: 0

Views: 996

Answers (1)

Andrei CACIO
Andrei CACIO

Reputation: 2119

I would create the following components:

  1. <MenuContainer /> -> our root component

  2. <Menu></Menu> -> can render either itself (<Menu />) or an <Item /> component

  3. <Item></Item> -> can render only a <li /> or smth

And suppose we have the following JSON coming from our server:

{
  label: 'Some menu',
  children: [{ label: 'Sub menu', children: [...] }, ...],
}

Let assume that when we find an array in our JSON, that means that we have to render a menu. If we have an object, we render a simple child. A rough algorithm would be:

const MenuContainer = ({items}) => ({
   {items.map(item => item.items ? <Menu items={items} /> : <Item data={item} /> }
});

Is this something you are looking for?

Upvotes: 1

Related Questions