JSFiddle - React, Tailwind, and code Playground
HTML
<div id="wrapper"></div>
CSS
#wrapper {
position: relative;
}
.component {
position: absolute;
border: 1px solid #000;
height: 30px;
padding: 5px;
width: 90px;
}
JavaScript
var jsonObj = {
id: "window1",
name: "Corporate",
children: [
{ id: "window12", name:"IT", children: [
{ id: "window121", name:"Dev", children: [] },
{ id: "window122", name:"Web", children: [] }
] },
{ id: "window13", name:"HR", children: [
{ id: "window121", name:"Dev", children: [] },
{ id: "window122", name:"Web", children: [] },
{ id: "window122", name:"Web", children: [] }
] },
{ id: "window14", name:"Finance", children: [] }
]
};
var create_graph_components = function (json, level, offsetStart) {
var offsetEnd = offsetStart;
for (var i = 0; i < json.children.length; i++) {
offsetEnd = create_graph_components(json.children[i], level + 1, offsetEnd);
}
var offset;
if (json.children.length == 0) {
offset = offsetEnd;
// Node is a leaf therefore extend offsetEnd
offsetEnd += 50;
} else {
// Calculates position halfway between child nodes
offset = offsetStart + (offsetEnd - offsetStart - 50) / 2;
// Node is a branch therefore we do not extend the offsetEnd
}
// Create the element
var child = $('<div id="' + json.id + '" class="component window">' +
'<strong>' + json.name + '</strong>' +
'</div>');
// Position the element
child.css({
top: offset + "px",
left: level * 150 + "px"
});
// Add it to the wrapper
$("#wrapper").append(child);
return offsetEnd;
};
create_graph_components(jsonObj, 0, 0);