Being relatively new to d3, I have been struggling with understanding data joins. My current challenge involves adding rows to a grid layout, where each row is represented as an object with multiple slots stored in an array.
Within my .join
, I am attempting to add multiple elements to the selection (with content based on the slots of the object, specifically the .text
). However, I am facing difficulties in specifying the .selectAll
call prior to the .data
call. I realize why this behavior is occurring – it tries to match the data with all divs in the selection (which are essentially all cells).
How should I modify my code so that each button click simply adds a new row?
Additionally, how can I ensure that the cells are added by row and not by column?
const data = [
{cell1: '1/1', cell2: '1/2', cell3: '1/3', id: 1},
{cell1: '2/1', cell2: '2/2', cell3: '2/3', id: 2}
];
function update(data) {
d3.select('#grid')
.selectAll('div')
.data(data, (d) => d.id)
.join((enter) => {
enter.append('div')
.classed('cell1', true)
.text((d) => d.cell1);
enter.append('div')
.classed('cell2', true)
.text((d) => d.cell2)
enter.append('div')
.classed('cell3', true)
.text((d) => d.cell3);
})
}
update(data)
function addRow() {
const n = data.length + 1;
const newRow = {cell1: n + '/1', cell2: n + '/2', cell3: n + '/3', id: n};
data.push(newRow);
update(data);
}
#grid {
display: inline-grid;
grid-template-columns: repeat(3, 200px);
}
#grid > div:nth-of-type(3n+2) {
background-color: orange;
}
#grid > div:nth-of-type(3n+1) {
background-color: purple;
}
#grid > div:nth-of-type(3n+0) {
background-color: forestgreen;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>
<div id="grid">
</div>
<button id="add" onclick="addRow()">Add Row</button>