I'm trying to make a legend for my graph using d3, and I figured I could use a table with the following HTML for each row:
<tr>
<td class="swatch" style="background: red;"></td>
<td>user</td>
<td>123</td>
</tr>
The end result looks something like this.
I have my data neatly placed on each row in the following form:
{color: 'red', key: 'user', value: 123}
And I'm using this code to create the cells:
let cells = d3.selectAll('tr').selectAll('td')
.data(function (d) {
return [d.color, d.key, d.value];
});
cells.enter().append('td').merge(cells)
.text(function (d, i) {
return i == 0 ? '' : d;
})
.style('background', function(d, i) {
return i == 0 ? d : '';
})
.each(function(d, i) {
if (i == 0) {
this.classList.add('swatch');
}
});
The code works fine, but it looks really ugly with the repeated i == 0
checks to special-case the behavior for the first cell. Is there a cleaner approach I could be using?
It seems like maybe I should be setting everything using text
and using CSS to style it into a swatch of color, but that isn't possible.