JSFiddle - React, Tailwind, and code Playground

by Nivaldo

HTML

<div id="data-field"></div>
<button id="add-btn">Add Data</button>
<p>Click on a bar to remove it</p>

CSS

.chart rect {
    fill: teal;
}
.chart text {
    fill: white;
    font: 30px sans-serif;
    text-anchor: end;
}

JavaScript

var barHeight = 75, margin = 3, padding = 3, i=0;

var chartData = [6,12,15,21,29,41];

var chart = d3.select("body")
    .append("svg")
    .attr("class","chart")
    .attr("width", 600)
    .attr("height", 600);

drawChart();

function drawChart() {
    
    var selection = chart.selectAll("g")
        .data(chartData);
    
    // Remove extra bars
    selection.exit()
        .remove();
    
    // Add more bars
    var groups = selection.enter()
        .append("g");
    
    var bars = groups
        .append("rect");
    
    var labels = groups
        .append("text");
    
    // Update existing bars; do not use groups here since it represents
    // only the ENTER selection, and not ALL g elements
    selection
        .attr("transform", function (d, i) { return "translate(0," + i * (barHeight + margin) + ")"; })
        .on("click", function (d, i) { 
            d3.select(this).remove(); // remove appropriate DOM element
            chartData.splice(i, 1); 
            drawChart(); 
        });      
    
    bars
        .attr("width", function (d) { return d * 10 + "px"; })
        .attr("height", barHeight);		
    
    labels
        .attr("x", function (d) { return d * 10 - padding + "px"; })
        .attr("y", barHeight / 3 + padding + "px")
        .text(function (d) { return d; });
    
    // update list of numbers
    d3.select("#data-field").text("numbers: [" + chartData.join(", ") + "]");
}

// add more data
d3.select("#add-btn")
    .on("click", function(d) { 
        chartData.push((Math.round(Math.random() * 50) + 1)); 
        drawChart(); 
    });