JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<head>
<script src="https://d3js.org/d3.v5.js"></script>
<title>Update pattern</title>
</head>
<body>
<svg width="400" height="400"></svg>
<style>
text {
font: bold 48px monospace;
}
.enter {
fill: green;
}
.update {
fill: #333;
}
</style>
</body>
</html>
JavaScript
let svg = d3.select('svg');
function update(data){
let objects = svg.selectAll("rect").data(data, function(d){ return d.id; });
objects.x = 300;
objects.enter().append("rect") // ENTER
.style("fill", function(d){
return d.color;
})
.attr('width', 50)
.attr('height', 50)
.attr('x', function(d){
return d.x;
})
.attr('y', function(d){
return d.y;
})
//.merge(objects) // ENTER + UPDATE
.style("stroke", "black");
// objects.exit().remove();
}
update([{id: 1, x: 0, y: 0, color: 'red'}, {id: 2, x:100, y: 100, color: 'green'}]);
setTimeout(function(){
update([{id: 1, x: 200, y: 0, color: 'red'}]);
alert('updated');
}, 2000);
/*
setTimeout(function(){
update([{id: 3, x: 200, y: 200, color: 'yellow'}])
}, 1500);
*/