Div vs SVG for Javascript Treemap
I need a treemap like the one from plotly: https://plotly.com/python/treemaps/ for a react application, which supports a zoom functionality, so that multiple layers can be explored, without the need to show all layers at once. I can't use plotly, because it seems to violate the CSP and I could not find any other library, with an example that worked for me.
I know think about writing a custom treemap component. Every treemap I tried was built as SVG. However, I have no experience with SVG's and would prefer to build the treemap with div elements. Since I could not find any solution that uses div elements, I wonder if there is any pitfall, which I don't know about.
I know that too many DOM elements might be a problem. But I don't need to show more than 2 layers at once, which are never more than 200 elements.
Solution 1:
This example is the beginning of something that could take form as a tree. It is made with divs based on the object data
.
I began to style it, but it takes some experimentation and structuring...
const data = {
'1': {
'1.1': {
'1.1.1': {}
},
'1.2': {}
},
'2': {
'2.1': {},
'2.2': {
'2.2.1': {},
'2.2.2': {}
}
}
};
const tree = document.getElementById('tree');
const insertchildren = (parent, obj, level) => {
Object.keys(obj).forEach(key => {
let child = document.createElement('div');
child.setAttribute('class', `node v${Object.keys(obj[key]).length} l${level}`);
let title = document.createElement('div');
title.setAttribute('class', 'title');
title.textContent = key;
child.appendChild(title);
parent.appendChild(child);
insertchildren(child, obj[key], level + 1);
});
};
insertchildren(tree, data, 1);
div#tree {
display: flex;
flex-direction: row;
}
.l1 {
flex-direction: column;
}
.l2 {
flex-direction: row;
}
.l3 {
flex-direction: column;
}
div.node {
display: flex;
padding: 2px;
border: solid thin black;
margin: 2px;
box-sizing: border-box;
}
.title {
width: 100%;
}
.v0 {
height: 100px;
}
<div id="tree" class="v2"></div>