Reputation: 102
need to use the data value in tree format. It should automatically create a new node if there is another child
<Tree
key={index}
lineWidth={"2px"}
lineColor={"green"}
lineBorderRadius={"10px"}
label={
<StyledNode>
{data.name}
</StyledNode>
}
>
{data.subordinates.map((data, index) => {
return (
<TreeNode
key={index}
label={
<StyledNode>
{data.name}
</StyledNode>
}
></TreeNode>
);
})}
</Tree>
I want to create the new node on the basis of the JSON received and sample JSON data is like;
export const chartData1 = [
{
name: "root",
sub: [
{ name: "child1", sub: [{ name: "schild1", sub: [] }] },
{ name: "child2", sub: [{ name: "schild2", sub: [] }] },
],
},
{
name: "roo2",
sub: [
{ name: "child1", sub: [] },
{ name: "child2 DOE", sub: [] },
],
},
];
Upvotes: 0
Views: 1187
Reputation: 2217
I also had a similar case.
And created a component for this feature. might be useful for the users who are searching for the same.
A fully customizable lightweight tree generator component.
You can pass custom child and parent components for a better view
https://www.npmjs.com/package/react-custom-tree
Upvotes: 0
Reputation: 2866
This is the simplest solution. Just style your div
s as you like.
function TreeNode({ node }) {
if (node.sub.length === 0) {
return <div>{node.name}</div>;
} else {
return (
<div>
<p>{node.name}</p>
{node.sub.map(x => (
<TreeNode node={x} />
))}
</div>
);
}
}
Checkout how it works in the CodeSandbox
Upvotes: 4