JSFiddle - React, Tailwind, and code Playground

by Sulthan Allaudeen

HTML

<script src="https://d3js.org/d3.v5.js"></script>
<svg width="800" height="550"></svg>

CSS

.node circle {
  fill: #999;
}

.node text {
  font: 12px sans-serif;
}

.node--internal circle {
  fill: #555;
}

.link {
  fill: none;
  stroke: #555;
  stroke-opacity: 0.4;
  stroke-width: 1.5px;
}

JavaScript

var data = {
  "name": "Root",
  "children": [
    {
      "name": "Branch 1",
      "children": [
        {"name": "Leaf 3",
        "children": [
        {"name": "Leaf 5"}]
        },
        {"name": "Leaf 4"}
      ]
    },
    {"name": "Branch 2"}
  ]
}

var split_index = Math.round(data.children.length / 2)

// Left data
var data1 = {
  "name": data.name,
  "children": JSON.parse(JSON.stringify(data.children.slice(0, split_index)))
};

// Right data
var data2 = {
  "name": data.name,
  "children": JSON.parse(JSON.stringify(data.children.slice(split_index)))
};

// Create d3 hierarchies
var right = d3.hierarchy(data1);
var left = d3.hierarchy(data2);

// Render both trees
drawTree(right, "right")
drawTree(left, "left")

// draw single tree
function drawTree(root, pos) {

  var SWITCH_CONST = 1;
  if (pos === "left") {
    SWITCH_CONST = -1;
  }

  var svg = d3.select("svg"),
    width = +svg.attr("width"),
    height = +svg.attr("height")

  // Shift the entire tree by half it's width
  var g = svg.append("g").attr("transform", "translate(" + width / 2 + ",0)");

  // Create new default tree layout
  var tree = d3.tree()
    // Set the size
    // Remember the tree is rotated
    // so the height is used as the width
    // and the width as the height
    .size([height, SWITCH_CONST * (width - 150) / 2]);

  tree(root)

  var nodes = root.descendants();
  var links = root.links();
  // Set both root nodes to be dead center vertically
  nodes[0].x = height / 2

  // Create links
  var link = g.selectAll(".link")
    .data(links)
    .enter()

  link.append("path")
    .attr("class", "link")
    .attr("d", function(d) {
      return "M" + d.target.y + "," + d.target.x + "C" + (d.target.y + d.source.y) / 2.5 + "," + d.target.x + " " + (d.target.y + d.source.y) / 2 + "," + d.source.x + " " + d.source.y + "," + d.source.x;
    });

  // Create nodes
  var node = g.selectAll(".node")
    .data(nodes)
    .enter()
    .append("g")
    .attr("class", function(d) {
...