const treeItems = [
{
id: 1,
name: 'English',
country: 'US',
children: [
{
id: 4,
name: 'Spring',
country: 'Uk',
children: []
}
]
},
{
id: 14,
name: 'Italian',
country: 'AUS',
children: [
{
id: 24,
name: 'Level A',
country: 'IND',
children: []
}
]
}
]
I have data in tree format it can be hierarchical or flat so I have used tree view. But I also want to display all columns inside the node which is id, name & country in table view inside tree view.
I am using Treeview from material UI I checked the documentation as well. I didn't find any solution yet.
Below is the format I want to display
ID Name Country
------------------------------------------
1 English US
4 SPring Uk
14 Italian Aus
24 Level A IND
The solution is a little bit more tricky than MUI TreeView example. While example accepts data as JSON, in your case you have an array of JSON.
Supposing that you want to show name
attribute in treeview label, you could write something like this:
<TreeView
className={classes.root}
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpanded={["root"]}
defaultExpandIcon={<ChevronRightIcon />}
>
{renderTree(data)} //<-- this is the function that recursively inspects your array
</TreeView>
Then the renderTree
function:
const renderTree = (nodes) => {
return nodes.map((el) => { //<-- mapping on array
return (
<TreeItem key={el.id} nodeId={el.id.toString()} label={el.id + " " + el.name + " " + el.country}>
{Array.isArray(el.children) && el.children.length > 0
? renderTree(el.children) //<-- recursion in case children has values
: null}
</TreeItem>
);
});
};
The result is:
Here a working example.