1

I have a hierarchical object. Looks like this:

{
  id: 74,
  parentId: null,
  children: [
    {
      id: 62,
      parentId: 74,
      children: [{ id: 56, parentId: 62 }, { id: 63, parentId: 62 }],
    },
    {
      id: 86,
      parentId: 74,
      children: [
        {
          id: 80,
          parentId: 86,
          children: [{ id: 81, parentId: 80 }, { id: 76, parentId: 80 }],
        },
        { id: 87, parentId: 86 },
      ],
    },
  ],
};

I want to display it on my front end using the tree view module I got from the https://mui.com/material-ui/react-tree-view/ The syntax for tree view is like this:

 return (
    <TreeView
      aria-label="file system navigator"
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpandIcon={<ChevronRightIcon />}
      sx={{ height: 240, flexGrow: 1, maxWidth: 400, overflowY: 'auto' }}
    >
      <TreeItem nodeId="1" label="Applications">
        <TreeItem nodeId="2" label="Calendar" />
      </TreeItem>
      <TreeItem nodeId="5" label="Documents">
        <TreeItem nodeId="10" label="OSS" />
        <TreeItem nodeId="6" label="MUI">
          <TreeItem nodeId="8" label="index.js" />
        </TreeItem>
      </TreeItem>
    </TreeView>
  );
}

How can I loop over my object and enter the respective values into the parents and corresponding children tree items inside this tree syntax? It should look like this:

<TreeItem nodeId="74" label="74">
 <TreeItem nodeId="62" label="62">
  <TreeItem nodeId="52" label="52"/>
 <TreeItem />
.
.
.
<TreeItem />

1 Answer 1

2

you can do something like this

const renderTree = tree => {
  return <TreeItem key={tree.id} nodeId={tree.id} label={tree.id}>
          {tree.children && tree.children.map(renderTree)}
       </TreeItem>

} 


return (
    <TreeView
      aria-label="file system navigator"
      defaultCollapseIcon={<ExpandMoreIcon />}
      defaultExpandIcon={<ChevronRightIcon />}
      sx={{ height: 240, flexGrow: 1, maxWidth: 400, overflowY: 'auto' }}
    >
      {renderTree(tree)}
    </TreeView>
  );
Sign up to request clarification or add additional context in comments.

1 Comment

thank you so much! Now all I need is to write a condition so that only the lowest level children are clickable buttons (In my actual project on clicking the names of the said children, they will be passed as props to another component called inside the functional component where I'm making the tree view)

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.