Reputation: 25
I have a an array which looks similar to this:
const hierarchy = [
{
hierarchyId: 1,
hierarchyName: 'John'
children: [
{
hierarchyId: 2,
hierarchyName: 'Mary',
children: []
},
{
hierarchyId: 3,
hierarchyName: 'Jane',
children: [
{
hierarchyId: 4,
hierarchyName: 'Joan',
children: []
},
{
hierarchyId: 5,
hierarchyName: 'Jim',
children: [
{
hierarchyId: 6,
hierarchyName: 'Mike',
children: []
}
]
}
]
}
]
}
]
And I want to represent this on an Ant Design Tree. But I want to be able to add buttons and possibly another column to a TreeNode in the Tree.
import React from 'react'
import { Tree } from 'antd'
const { TreeNode } = Tree
const TreeComponent = ({ hierarchy }) => {
return (
<Tree>
{hierarchy.map(res => {
return (
<TreeNode
key={res.hierarchyId}
title={(
<div>
<span>{res.hierarchyName}</span>
<span>Another Column</span>
<button>Click here</button>
</div>
)}>
{res.children.map(r => {
<TreeNode
key={res.hierarchyId}
title={(
<div>
<span>{res.hierarchyName}</span>
<span>Another Column</span>
<button>Click here</button>
</div>
)} />
})}
</TreeNode>
)
}}
</Tree>
)
}
export default TreeComponent
Now obviously the above would only show 2 levels deep in the tree, I'm wondering if there were say 10 levels (or any amount really) how I would dynamically display each level in the tree without knowing how deep it goes and still be able to add a button and another column to the TreeNode?
Any help is greatly appreciated, thanks!
Upvotes: 0
Views: 6337
Reputation: 25
I ended up using this simple solution:
import React from 'react'
import { Tree } from 'antd'
const { TreeNode } = Tree
const TreeComponent = ({ hierarchy }) => {
const renderTreeNodes = data =>
data.map(item => {
if (item.children) {
return (
<TreeNode title={item.title} key={item.key} dataRef={item}>
{renderTreeNodes(item.children)}
</TreeNode>
)
}
return <TreeNode key={item.key} {...item} />
})
return (
<Tree>
{renderTreeNodes(hierarchy)}
</Tree>
)
}
export default TreeComponent
Which I found here: Ant design Tree defaultExpandAll doesnt work with button click for react
Upvotes: 2