Arun K Anil
Arun K Anil

Reputation: 105

How to render a custom node for @nivo/tree

I am trying to make a tree structure in react. I was trying with @nivo/tree. There's very limited documentation for this library. I couldn't get it to render a custom node. Attaching the code here.

import React from "react";
import { ResponsiveTree } from "@nivo/tree";


const CustomNode = ({ node, x, y, isActive }) => (
  <g transform={`translate(${x}, ${y})`}>
    {/* Circle to represent the node */}
    <circle r={isActive ? 22 : 18} fill={node.data.color} stroke="#000" strokeWidth={isActive ? 3 : 1} />

    {/* Node text */}
    <text x={0} y={5} textAnchor="middle" fontSize={12} fill="#333">
      {node.data.name}
    </text>

    {/* Additional node details, e.g., loc */}
    {node.data.loc && (
      <text x={0} y={20} textAnchor="middle" fontSize={10} fill="#777">
        Loc: {node.data.loc}
      </text>
    )}
  </g>
);

const Tree = (data) => {
  return (
    <div style={{ height: 600, width: "100%" }}>
      <ResponsiveTree
        data={data}
        identity="id"
        mode="tree"
        layout="bottom-to-top"
        nodeSize={40}
        activeNodeSize={44}
        inactiveNodeSize={32}
        nodeColor={{ scheme: "tableau10" }}
        fixNodeColorAtDepth={1}
        linkCurve="step-before"
        linkThickness={2}
        activeLinkThickness={8}
        inactiveLinkThickness={2}
        linkColor={{
          from: "target.color",
          modifiers: [["opacity", 0.4]],
        }}
        labelsPosition="layout-opposite"
        orientLabel={false}
        margin={{ top: 90, right: 90, bottom: 90, left: 90 }}
        meshDetectionRadius={80}
        nodeComponent={CustomNode} // Custom node component
      />
    </div>
  );
};

export default Tree;

Current tree rendered

This is the tree currently rendered. The nodes are not appearing properly.

Upvotes: 0

Views: 40

Answers (0)

Related Questions