JSFiddle - React, Tailwind, and code Playground

by javajosh

HTML

<p>Editable demo of d3's tree layout. This is a bit of a mashup between the <a href="http://bl.ocks.org/mbostock/4339184">main demo</a> and the <a href="https://github.com/mbostock/d3/wiki/Tree-Layout">d3's tree layout docs</a></p>

CSS

.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 1.5px;
}

.node {
  font: 10px sans-serif;
}

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 1.5px;
}

JavaScript

var a = {name: 'alice'};
var b = {name: 'bob'};
var c = {name: 'charlie'};

//if you include alice as a child of herself, you'll crash the browser. 
//cloning solves that problem.
//problems remain if we repeat *any* node.
//also solved by cloning. To be safe, if we 
//are constructing a tree of reused nodes, 
//ALWAYS CLONE

function clone(o){return JSON.parse(JSON.stringify(o));}
b.children = [clone(c)];
a.children = [clone(a), b,c];
         

var root = a;

var width = 300,
    height = 200;

var tree = d3.layout.tree()
    .size([height, width - 160]);

var diagonal = d3.svg.diagonal()
    .projection(function(d) { return [d.y, d.x]; });

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
  .append("g")
    .attr("transform", "translate(40,0)");

var nodes = tree.nodes(root),
    links = tree.links(nodes);

var link = svg.selectAll("path.link")
    .data(links)
    .enter().append("path")
    .attr("class", "link")
    .attr("d", diagonal);

var node = svg.selectAll("g.node")
    .data(nodes)
    .enter().append("g")
    .attr("class", "node")
    .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })

node.append("circle")
    .attr("r", 4.5);

node.append("text")
    .attr("dx", function(d) { return d.children ? -8 : 8; })
    .attr("dy", 3)
    .attr("text-anchor", function(d) { return d.children ? "end" : "start"; })
    .text(function(d) { return d.name; });