0

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: [] },
    ],
  },
];

2 Answers 2

4

This is the simplest solution. Just style your divs 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

Sign up to request clarification or add additional context in comments.

7 Comments

if we have more child then, it is not working @Rostyslav
@SanuKumar have you checked the sandbox ?
Yes, i have checked the sandbox, but my current JSON have more number of childs
can you provide the JSON?
It does work for the JSON format which you provided...
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.