JSFiddle - React, Tailwind, and code Playground
HTML
<!DOCTYPE html>
<body>
CSS
.link {
stroke: #000;
stroke-width: 1.5px;
}
.node {
fill: #000;
stroke: #fff;
stroke-width: 1.5px;
}
.node text {
font: 10px sans-serif;
pointer-events: none;
text-anchor: middle;
}
.node.a { fill: #1f77b4; }
.node.b { fill: #ff7f0e; }
.node.c { fill: #2ca02c; }
JavaScript
var width = 960,
height = 500;
var nodeId=[{id:"b"},{id:"c"},{id:"d"},{id:"e"}];
var index=0;
var color = d3.scale.category10();
var nodes = [],
links = [];
var force = d3.layout.force()
.nodes(nodes)
.links(links)
.charge(-400)
.linkDistance(120)
.gravity(.05)
.size([width, height])
.on("tick", tick);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var node = svg.selectAll(".node"),
link = svg.selectAll(".link");
// 1. Add three nodes and three links.
var a = {id: "a"};
nodes.push(a);
console.log(nodes);
console.log(links);
start();
function start() {
force.nodes(nodes)
.links(links)
.start();
link = link.data(force.links(), function(d) { return d.target.id; });
link.exit().remove();
link.enter().insert("line", ".node").attr("class", "link");
node = node.data(force.nodes(), function(d) { return d.id;});
node.exit().remove();
var nodeEnter = node.enter().append("g")
.on("click", click)
.call(force.drag);
nodeEnter.append("circle")
.attr("r", 8);
nodeEnter.append("text")
.attr("x", 10)
.attr("y", ".31em")
.text(function(d) { return d.id; });
node.select("circle")
.style("fill", color);
}
function click(d) {
if (d3.event.defaultPrevented) return; // ignore drag
//alert("clicked");
var d = {id:"d"};
nodes.push(nodeId[index]);
if(index==0)
links.push({source: a, target: nodeId[index]});
else
links.push({source: nodes[1], target: nodeId[index]});
index++;
start();
}
function tick() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}
function color(d) {
return d._children ?...