[英]I have a data coming from the api how do I display it in tree form in react
This is the following data that is coming from api I have to dispaly this data in the tree form这是来自 api 的以下数据我必须以树形形式显示这些数据
{
"Customers": {
"M": {
"age": 20,
"email": "m@kuchto.com",
"AA": null,
"DD": "555"
},
"Hh": {
"course": {
"c++": {
"duration": 3
}
}
}}
I am not sure if I need to use map function inside my render method to iterate and display the data and how will it work along.Can someone let me know if I am doing it right or is there any better way of doing it.我不确定我是否需要在我的渲染方法中使用 map function 来迭代和显示数据以及它将如何工作。有人可以告诉我我做得对还是有更好的方法。 thanks in advance.提前致谢。
There are many ways to approach this task.有很多方法可以完成这项任务。 You can create a component yourself to render the tree
structure or you can use UI frameworks like Material UI
to do the task for you.您可以自己创建一个组件来呈现tree
结构,也可以使用Material UI
等 UI 框架为您完成任务。 I think it's better not to re-invent the wheel here and use the UI framework.我认为最好不要在这里重新发明轮子并使用UI框架。 For example, Material UI
has a Tree
component for React
.例如, Material UI
有一个用于React
的Tree
组件。 You can sort of implement the structure like this.您可以像这样实现结构。
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import TreeView from '@material-ui/lab/TreeView';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import TreeItem from '@material-ui/lab/TreeItem';
const data = {
id: 'root',
name: 'Parent',
children: [
{
id: '1',
name: 'Child - 1',
},
{
id: '3',
name: 'Child - 3',
children: [
{
id: '4',
name: 'Child - 4',
},
],
},
],
};
const useStyles = makeStyles({
root: {
height: 110,
flexGrow: 1,
maxWidth: 400,
},
});
export default function RecursiveTreeView() {
const classes = useStyles();
const renderTree = (nodes) => (
<TreeItem key={nodes.id} nodeId={nodes.id} label={nodes.name}>
{Array.isArray(nodes.children) ? nodes.children.map((node) => renderTree(node)) : null}
</TreeItem>
);
return (
<TreeView
className={classes.root}
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpanded={['root']}
defaultExpandIcon={<ChevronRightIcon />}
>
{renderTree(data)}
</TreeView>
);
}
Another option is to use npm
packages like react-simple-tree-menu .另一种选择是使用npm
包,如react-simple-tree-menu 。 It's easy to implement.这很容易实现。 It has good documentation and you don't have to rely on a UI framework just to implement a tree view on a component.它有很好的文档,您不必仅仅依靠 UI 框架来在组件上实现树视图。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.