Converting a multi-level JSON menu to a multi-level JSX/HTML menu

徘徊边缘 提交于 2019-11-29 14:32:19

Here's a dynamically generated menu, using JSX and your sample data.

As you can see, we're recursively iterating over your menu items while building the JSX:

const renderMenu = items => {
  return <ul>
    { items.map(i => {
      return <li>
        <a href={i.link}>{ i.title }</a>
        { i.menu && renderMenu(i.menu) }
      </li>
    })}
  </ul>
}

const Menu = ({ data }) => {
  return <nav>
    <h2>{ data.title }</h2>
    { renderMenu(data.menu) }
  </nav>
}

ReactDOM.render(
  <Menu data={data} />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script>
  // The sample data is declared here, only to keep the React example short and clear
  const data = {
    "module_type": "menu",
    "title": "My Site",
    "menu": [{
        "link": "/home",
        "title": "Home"
      },
      {
        "link": "#",
        "title": "Fruit",
        "menu": [{
            "link": "/apples",
            "title": "Apples"
          },
          {
            "link": "/bananas",
            "title": "Bananas"
          },
          {
            "link": "/kiwi",
            "title": "Kiwi"
          },
          {
            "link": "/pears",
            "title": "Pears"
          }
        ]
      },
      {
        "link": "#",
        "title": "Vegetables",
        "menu": [{
            "link": "/carrots",
            "title": "Carrots"
          },
          {
            "link": "/celery",
            "title": "Celery"
          },
          {
            "link": "/potatoes",
            "title": "Potatoes"
          },
          {
            "link": "#",
            "title": "More",
            "menu": [{
                "link": "/thirdlevel1",
                "title": "3rd level menu"
              },
              {
                "link": "/thirdlevel2",
                "title": "3rd level two"
              }
            ]
          }
        ]
      },
      {
        "link": "/about",
        "title": "About"
      },
      {
        "link": "/contact",
        "title": "Contact"
      }
    ]
  }
</script>
<div id="container"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!