Home > Software engineering >  Recursively enter nested object into tree view component inside return statement of a React function
Recursively enter nested object into tree view component inside return statement of a React function

Time:05-12

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 />

CodePudding user response:

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>
  );
  • Related