JSFiddle - React, Tailwind, and code Playground

by Rajesh Danabal

HTML

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>D3 Expandable Tree</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <style>
      .node rect {
        stroke: steelblue;
        stroke-width: 2px;
      }

      .node text {
        font: 14px sans-serif;
        pointer-events: none;
      }

      .link {
        fill: none;
        stroke: #ccc;
        stroke-width: 2px;
      }
    </style>
  </head>
  <body>
    <svg width="960" height="600"></svg>

    <script>
      const sampleData = {
        id: "Grand__Total",
        label: "Grand Total",
        level: 0,
        children: [
          {
            id: "2022",
            label: "2022",
            level: 1,
            children: [
              { id: "2022__January", label: "January", level: 2 },
              { id: "2022__Feb", label: "Feb", level: 2 },
              { id: "2022__March", label: "March", level: 2 }
            ]
          },
          {
            id: "2023",
            label: "2023",
            level: 1,
            children: [
              { id: "2023__January", label: "January", level: 2 },
              { id: "2023__Feb", label: "Feb", level: 2 },
              { id: "2023__March", label: "March", level: 2 }
            ]
          },
          {
            id: "2024",
            label: "2024",
            level: 1,
            children: [
              { id: "2024__January", label: "January", level: 2 },
              { id: "2024__Feb", label: "Feb", level: 2 },
              { id: "2024__March", label: "March", level: 2 }
            ]
          }
        ]
      };

      const width = 960;
      const height = 600;

      const svg = d3.select("svg")
        .attr("width", width)
        .attr("height", height);

      const g = svg.append("g").attr("transform", "translate(80,40)");

      const root = d3.hierarchy(sampleData, d => d.children);
      root.x0 = height / 2;
      root.y0 = 0;

     ...