1

I'm trying to render menu values from a JSON. Considering that this is a multilevel menu, I'm trying to do a nested map to render the full menu.

const menu = {
  data:[
  {
    title: "Home",
    child: [
      {
        title: "SubLevel1",
        child: {
          title: "SubSubLevel1"
        }
      },
      {
        title: "SubLevel2",
        child: [
          {title: "SubSubLevel1"},
          {title: "SubSubLevel2"}
        ]
      }
    ]
  },
  {
    title: "About",
  },
  {
    title: "Contact",
  }
]}

And here is the part when I use the map function :

const MenuNavigation = () => {
    return (
        {menu.data.map((item) => ( 
            <div>
                <ul>{item.title}</ul> 
                {item.map((sub, id) =>
                    <li>{sub.child[id].title}</li>
                )} 
            </div>
        ))}
    )
};

I managed to render main level for the menu (Home, About, Contact), but how can I print sublevel & subsublevel values?

Another question: Is there a way to map recursively a tree structure?

3
  • Yes, you can render the menu recursively. But your menu does not have a consistent structure? If the subChild is replaced with child and text is replaced with title and project is replaced with title, then It is possible to do so. can you update the question like that then It is possible to give an answer only if possible. Commented Apr 28, 2021 at 12:48
  • @AmilaSenadheera I did as you asked, but don't you think it will create variables conflicts? Thanks for the help. Commented Apr 28, 2021 at 12:59
  • no conflicts will occur when you do it recursivly Commented Apr 28, 2021 at 13:39

1 Answer 1

2

Try below:

The menu should be like this. Your menu had one issue in child of "SubLevel1" not defined inside an array.

  const menu = {
    data: [
      {
        title: "Home",
        child: [
          {
            title: "SubLevel1",
            child: [{
              title: "SubSubLevel1",
            }],
          },
          {
            title: "SubLevel2",
            child: [{ title: "SubSubLevel1" }, { title: "SubSubLevel2" }],
          },
        ],
      },
      {
        title: "About",
      },
      {
        title: "Contact",
      },
    ],
  };

Render it recursively like below. I have added a margin-left to see the levels properly.

  const renderMenu = (menu) => {
    return menu.map((item) => (
        <div style={{ marginLeft: '25px' }}>
            {item.title}
            {item.child && renderMenu(item.child)}
        </div>
    ))
  }

  return <div>{renderMenu(menu.data)}</div>;

Output

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.