Unable to create a tree view in reactjs

I am trying to create a treeview in React.js. But I am not able to set it properly. Below is my code

App.js

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React from "react";
import TreeHierarchy from "./TreeHierarchy"; // Adjust path if necessary
const App = () => {
return (
<div style={{ padding: "20px" }}>
<h1>Bahria Hierarchy</h1>
<TreeHierarchy />
</div>
);
};
export default App;
</code>
<code>import React from "react"; import TreeHierarchy from "./TreeHierarchy"; // Adjust path if necessary const App = () => { return ( <div style={{ padding: "20px" }}> <h1>Bahria Hierarchy</h1> <TreeHierarchy /> </div> ); }; export default App; </code>
import React from "react";
import TreeHierarchy from "./TreeHierarchy"; // Adjust path if necessary

const App = () => {
return (
<div style={{ padding: "20px" }}>
  <h1>Bahria Hierarchy</h1>
  <TreeHierarchy />
</div>
);
};

export default App;

TreeHierarchy.js

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import React from "react";
import { TreeView, TreeItem } from "@mui/x-tree-view";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";
// Sample hierarchy
const hierarchy = {
name: "Bahria",
precincts: [
{
name: "Precinct-1",
streets: [
{
name: "Road 1",
meters: ["3092000001", "3092000210"],
},
{
name: "Street 21",
meters: ["3092000012"],
},
],
},
],
};
// Recursive function to render the hierarchy tree
const TreeHierarchy = () => {
const renderTree = (node, parentId = "") => {
const nodeId = `${parentId}-${node.name || "node"}`;
return (
<TreeItem key={nodeId} nodeId={nodeId} label={node.name || "Unnamed"}>
{node.streets &&
node.streets.map((street, index) =>
renderTree(street, `${nodeId}-street-${index}`)
)}
{node.precincts &&
node.precincts.map((precinct, index) =>
renderTree(precinct, `${nodeId}-precinct-${index}`)
)}
{node.meters &&
node.meters.map((meter, index) => (
<TreeItem
key={`${nodeId}-meter-${index}`}
nodeId={`${nodeId}-meter-${index}`}
label={`Meter: ${meter}`}
/>
))}
</TreeItem>
);
};
return (
<TreeView
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronRightIcon />}
>
{renderTree(hierarchy)}
</TreeView>
);
};
export default TreeHierarchy;
</code>
<code>import React from "react"; import { TreeView, TreeItem } from "@mui/x-tree-view"; import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; import ChevronRightIcon from "@mui/icons-material/ChevronRight"; // Sample hierarchy const hierarchy = { name: "Bahria", precincts: [ { name: "Precinct-1", streets: [ { name: "Road 1", meters: ["3092000001", "3092000210"], }, { name: "Street 21", meters: ["3092000012"], }, ], }, ], }; // Recursive function to render the hierarchy tree const TreeHierarchy = () => { const renderTree = (node, parentId = "") => { const nodeId = `${parentId}-${node.name || "node"}`; return ( <TreeItem key={nodeId} nodeId={nodeId} label={node.name || "Unnamed"}> {node.streets && node.streets.map((street, index) => renderTree(street, `${nodeId}-street-${index}`) )} {node.precincts && node.precincts.map((precinct, index) => renderTree(precinct, `${nodeId}-precinct-${index}`) )} {node.meters && node.meters.map((meter, index) => ( <TreeItem key={`${nodeId}-meter-${index}`} nodeId={`${nodeId}-meter-${index}`} label={`Meter: ${meter}`} /> ))} </TreeItem> ); }; return ( <TreeView defaultCollapseIcon={<ExpandMoreIcon />} defaultExpandIcon={<ChevronRightIcon />} > {renderTree(hierarchy)} </TreeView> ); }; export default TreeHierarchy; </code>
import React from "react";
import { TreeView, TreeItem } from "@mui/x-tree-view";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ChevronRightIcon from "@mui/icons-material/ChevronRight";

// Sample hierarchy
const hierarchy = {
name: "Bahria",
precincts: [
{
  name: "Precinct-1",
  streets: [
    {
      name: "Road 1",
      meters: ["3092000001", "3092000210"],
    },
    {
      name: "Street 21",
      meters: ["3092000012"],
    },
    ],
    },
    ],
 };

// Recursive function to render the hierarchy tree
const TreeHierarchy = () => {
const renderTree = (node, parentId = "") => {
const nodeId = `${parentId}-${node.name || "node"}`;

return (
  <TreeItem key={nodeId} nodeId={nodeId} label={node.name || "Unnamed"}>
    {node.streets &&
      node.streets.map((street, index) =>
        renderTree(street, `${nodeId}-street-${index}`)
      )}
    {node.precincts &&
      node.precincts.map((precinct, index) =>
        renderTree(precinct, `${nodeId}-precinct-${index}`)
      )}
    {node.meters &&
      node.meters.map((meter, index) => (
        <TreeItem
          key={`${nodeId}-meter-${index}`}
          nodeId={`${nodeId}-meter-${index}`}
          label={`Meter: ${meter}`}
        />
      ))}
  </TreeItem>
);
};

return (
<TreeView
  defaultCollapseIcon={<ExpandMoreIcon />}
  defaultExpandIcon={<ChevronRightIcon />}
>
  {renderTree(hierarchy)}
</TreeView>
);
};

export default TreeHierarchy;

Output

When I click on the main node name I am getting below errors

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>MUI X: The Tree View component requires all items to have a unique `id` property.
Alternatively, you can use the `getItemId` prop to specify a custom id for each item.
Two items were provided with the same id in the `items` prop: "undefined"
Error: MUI X: The Tree View component requires all items to have a unique `id` property.
Alternatively, you can use the `getItemId` prop to specify a custom id for each item.
Two items were provided with the same id in the `items` prop: "undefined"
at http://localhost:3000/static/js/bundle.js:15169:15
at basicStateReducer (http://localhost:3000/static/js/bundle.js:37272:45)
at updateReducer (http://localhost:3000/static/js/bundle.js:37381:26)
at updateState (http://localhost:3000/static/js/bundle.js:37667:14)
at Object.useState (http://localhost:3000/static/js/bundle.js:38464:20)
at Object.useState (http://localhost:3000/static/js/bundle.js:54836:25)
at useTreeView (http://localhost:3000/static/js/bundle.js:16177:64)
at SimpleTreeView (http://localhost:3000/static/js/bundle.js:12473:83)
at renderWithHooks (http://localhost:3000/static/js/bundle.js:37072:22)
at updateForwardRef (http://localhost:3000/static/js/bundle.js:40321:24)
</code>
<code>MUI X: The Tree View component requires all items to have a unique `id` property. Alternatively, you can use the `getItemId` prop to specify a custom id for each item. Two items were provided with the same id in the `items` prop: "undefined" Error: MUI X: The Tree View component requires all items to have a unique `id` property. Alternatively, you can use the `getItemId` prop to specify a custom id for each item. Two items were provided with the same id in the `items` prop: "undefined" at http://localhost:3000/static/js/bundle.js:15169:15 at basicStateReducer (http://localhost:3000/static/js/bundle.js:37272:45) at updateReducer (http://localhost:3000/static/js/bundle.js:37381:26) at updateState (http://localhost:3000/static/js/bundle.js:37667:14) at Object.useState (http://localhost:3000/static/js/bundle.js:38464:20) at Object.useState (http://localhost:3000/static/js/bundle.js:54836:25) at useTreeView (http://localhost:3000/static/js/bundle.js:16177:64) at SimpleTreeView (http://localhost:3000/static/js/bundle.js:12473:83) at renderWithHooks (http://localhost:3000/static/js/bundle.js:37072:22) at updateForwardRef (http://localhost:3000/static/js/bundle.js:40321:24) </code>
MUI X: The Tree View component requires all items to have a unique `id` property.
Alternatively, you can use the `getItemId` prop to specify a custom id for each item.
Two items were provided with the same id in the `items` prop: "undefined"
Error: MUI X: The Tree View component requires all items to have a unique `id` property.
Alternatively, you can use the `getItemId` prop to specify a custom id for each item.
Two items were provided with the same id in the `items` prop: "undefined"
at http://localhost:3000/static/js/bundle.js:15169:15
at basicStateReducer (http://localhost:3000/static/js/bundle.js:37272:45)
at updateReducer (http://localhost:3000/static/js/bundle.js:37381:26)
at updateState (http://localhost:3000/static/js/bundle.js:37667:14)
at Object.useState (http://localhost:3000/static/js/bundle.js:38464:20)
at Object.useState (http://localhost:3000/static/js/bundle.js:54836:25)
at useTreeView (http://localhost:3000/static/js/bundle.js:16177:64)
at SimpleTreeView (http://localhost:3000/static/js/bundle.js:12473:83)
at renderWithHooks (http://localhost:3000/static/js/bundle.js:37072:22)
at updateForwardRef (http://localhost:3000/static/js/bundle.js:40321:24)

The tree structure is below

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Bharia (Parent node)
=> Precinct (value)
=>streets (value)
=> meters (value)
</code>
<code>Bharia (Parent node) => Precinct (value) =>streets (value) => meters (value) </code>
Bharia (Parent node)
  => Precinct (value)
      =>streets (value)
         => meters (value)

I am stuck to it and must be missing something. Any help would be highly appreciated.

1

Each TreeItem needs a unique itemId

… as stated in the documentation.

This is the changed renderTree function that respects this requirement:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>const renderTree = (node, parentId = "") => {
const nodeId = `${parentId}-${node.name || "node"}`;
return (
<TreeItem
key={nodeId}
// itemId added here
itemId={nodeId}
nodeId={nodeId}
label={node.name || "Unnamed"}
>
{node.streets &&
node.streets.map((street, index) =>
renderTree(street, `${nodeId}-street-${index}`)
)}
{node.precincts &&
node.precincts.map((precinct, index) =>
renderTree(precinct, `${nodeId}-precinct-${index}`)
)}
{node.meters &&
node.meters.map((meter, index) => {
// an `id` constant to avoid repeating code
const id = `${nodeId}-meter-${index}`;
return (
<TreeItem
key={id}
// ...and another itemId here
itemId={id}
nodeId={`${nodeId}-meter-${index}`}
label={`Meter: ${meter}`}
/>
);
})}
</TreeItem>
);
};
</code>
<code>const renderTree = (node, parentId = "") => { const nodeId = `${parentId}-${node.name || "node"}`; return ( <TreeItem key={nodeId} // itemId added here itemId={nodeId} nodeId={nodeId} label={node.name || "Unnamed"} > {node.streets && node.streets.map((street, index) => renderTree(street, `${nodeId}-street-${index}`) )} {node.precincts && node.precincts.map((precinct, index) => renderTree(precinct, `${nodeId}-precinct-${index}`) )} {node.meters && node.meters.map((meter, index) => { // an `id` constant to avoid repeating code const id = `${nodeId}-meter-${index}`; return ( <TreeItem key={id} // ...and another itemId here itemId={id} nodeId={`${nodeId}-meter-${index}`} label={`Meter: ${meter}`} /> ); })} </TreeItem> ); }; </code>
const renderTree = (node, parentId = "") => {
  const nodeId = `${parentId}-${node.name || "node"}`;

  return (
    <TreeItem
      key={nodeId}
      // itemId added here
      itemId={nodeId}
      nodeId={nodeId}
      label={node.name || "Unnamed"}
    >
      {node.streets &&
        node.streets.map((street, index) =>
          renderTree(street, `${nodeId}-street-${index}`)
        )}
      {node.precincts &&
        node.precincts.map((precinct, index) =>
          renderTree(precinct, `${nodeId}-precinct-${index}`)
        )}
      {node.meters &&
        node.meters.map((meter, index) => {
          // an `id` constant to avoid repeating code
          const id = `${nodeId}-meter-${index}`;
          return (
            <TreeItem
              key={id}
              // ...and another itemId here
              itemId={id}
              nodeId={`${nodeId}-meter-${index}`}
              label={`Meter: ${meter}`}
            />
          );
        })}
    </TreeItem>
  );
};

In the code above, I’ve added a unique itemId property to each TreeItem.
I’ve also added an id constant in your node.meters.map(...) function argument, to avoid repeating the template string literal.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật