JSFiddle - React, Tailwind, and code Playground

by Brandon

JavaScript

function pieChart() {
  var _chart = {};
  var _width = 500,
    _height = 500,
    _data = [],
    _colors = d3.scaleOrdinal(d3.schemeCategory10),
    _svg,
    _bodyG,
    _pieG,
    _radius = 500,
    _innerRadius = 0,
    _duration = 2000;
  _chart.render = function() {
    if (!_svg) {
      _svg = d3.select("body").append("svg")
        .attr("height", _height)
        .attr("width", _width);
    }
    renderBody(_svg);
  };

  function renderBody(svg) {
    if (!_bodyG)
      _bodyG = svg.append("g")
      .attr("class", "body");
    renderPie();
  }

  function renderPie() {
    var pie = d3.pie() // <-A
      .sort(function(d) {
        return d.id;
      })
      .value(function(d) {
        return d.value;
      });
    var arc = d3.arc()
      .outerRadius(_radius - 10)
      .innerRadius(_innerRadius);
    if (!_pieG)
      _pieG = _bodyG.append("g")
      .attr("class", "pie")
      .attr("transform", "translate(" +
        _radius +
        "," +
        _radius + ")");
    renderSlices(pie, arc);
    renderLabels(pie, arc);
  }

  function renderSlices(pie, arc) {
    var slices = _pieG.selectAll("path.arc")
      .data(pie(_data)); // <-B
    slices.enter()
      .append("path")
      .merge(slices)
      .attr("class", "arc")
      .attr("fill", function(d, i) {
        return _colors(i);
      })
      .transition()
      .duration(_duration)
      .attrTween("d", function(d) {
        var currentArc = this.__current__; // <-C
        if (!currentArc)
          currentArc = {
            startAngle: 0,
            endAngle: 0
          };
        var interpolate = d3.interpolate(
          currentArc, d);
        this.__current__ = interpolate(1); //<-D
        return function(t) {
          return arc(interpolate(t));
        };
      });
  }

  function renderLabels(pie, arc) {
    var labels = _pieG.selectAll("text.label")
      .data(pie(_data)); // <-E
    labels.enter()
      .append("text")
      .merge(labels)
      .attr("class",...