JSFiddle - React, Tailwind, and code Playground

by Tim Williams

HTML

<script src="/d3/d3/d3.v3.min.js"></script>

JavaScript

var rectData = [
  { "label":"one",   "x": 100, "y": 50,  "height": 100, "width":120, "color" : "green" },
  { "label":"two",   "x": 250, "y": 50,  "height": 100, "width": 120, "color" : "purple"},
  { "label":"three", "x": 400, "y": 50,  "height": 100, "width": 120, "color" : "red"}
];

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

var rects = svg.selectAll("rect")
  .data(rectData)
  .enter();

rects.append("rect")
  .attr("x",     function (d)  { return d.x; })
  .attr("y",     function (d)  { return d.y; })
  .attr("height", function (d) { return d.height; })
  .attr("width",  function (d) { return d.width; })
  .style("fill",  function(d)  { return d.color; })
  .on('mouseover', function(d){
    var rectSelection = d3.select(this)
    .style({opacity:'0.5'})})
  .on('mouseout', function(d){
    var rectSelection = d3.select(this)
    .style({opacity:'1'})})
  .on("click", function(d){
    console.log("You clicked rectangle: " + d.label)
    console.log ("X position: " + d.x)
    console.log ("Y position: " + d.y)
  });

// Rectangle Label
rects.append("text")
  .style("fill", "black")
  .attr("dy", ".35em")
  .attr("x", function(d) { return d.x +10;})
  .attr("y", function(d) { return d.y +10;})
  .text(function(d) { return "Label: " + d.label });