JSFiddle - React, Tailwind, and code Playground

by Maria Karanasou

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.8.0/d3.js"></script>

CSS

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

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

.node--internal text {
  text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
}

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

JavaScript

var result = [
      { "id": 1, "name": "Top Level", "parent": null, "parentId": null },
      { "id": 2, "name": "PROD", "parent": "Top Level", "parentId": 1 },
      { "id": 3, "name": "QAT", "parent": "Top Level", "parentId": 1 },
      { "id": 4, "name": "App1", "parent": "PROD", "parentId": 2 },
      { "id": 5, "name": "App1", "parent": "QAT", "parentId": 3 },
      { "id": 6, "name": "ServerPROD001", "parent": "App1", "parentId": 4 },
      { "id": 7, "name": "ServerQAT001", "parent": "App1", "parentId": 5 }
    ];
    
   // convert the flat data into a hierarchy 
var treeData = d3.stratify()
.id(function (d) { return d.id; })
.parentId(function (d) { return d.parentId })
(result);
          
 console.log(treeData)
 
 
 // assign the name to each node
treeData.each(function(d) {
    d.name = d.data.name;
  });

// set the dimensions and margins of the diagram
var margin = {top: 20, right: 90, bottom: 30, left: 90},
    width = 660 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// declares a tree layout and assigns the size
var treemap = d3.tree()
    .size([height, width]);

//  assigns the data to a hierarchy using parent-child relationships
var nodes = d3.hierarchy(treeData, function(d) {
    return d.children;
  });

// maps the node data to the tree layout
nodes = treemap(nodes);

// append the svg object to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom),
    g = svg.append("g")
      .attr("transform",
            "translate(" + margin.left + "," + margin.top + ")");

// adds the links between the nodes
var link = g.selectAll(".link")
    .data( nodes.descendants().slice(1))
  .enter().append("path")
    .attr("class", "link")
    .attr("d", function(d) {
       return "M" + d.y + "," + d.x
         +...