React Pie Chart

In this example below you will see how to do a React Pie Chart with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by Hiswe, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright Hiswe ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>React Pie Chart</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  <div id="root"></div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/react/16.3.0/umd/react.development.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.3.0/umd/react-dom.development.js'></script>

  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/Hiswe/react-pie-chart-geyoxr */
html, body {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: sans-serif;
}

p {
  text-align: center;
  line-height: 1.4;
}

a {
  color: DeepPink;
  text-decoration: none;
}

.pie-chart {
  --pie-size: 200px;
  --pie-bg: MidnightBlue;
  --slice-1-bg: MediumPurple;
  --slice-2-bg: DarkSlateBlue;
  --slice-3-bg: DarkMagenta;
}
.pie-chart__title {
  text-align: center;
  text-transform: uppercase;
}
.pie-chart__pie {
  transform: rotate(-90deg);
  height: var(--pie-size);
  width: var(--pie-size);
  display: block;
  margin: 0 auto;
}
.pie-chart__pie_bg {
  fill: var(--pie-bg);
}
.pie-chart path:nth-of-type(1) {
  fill: var(--slice-1-bg);
}
.pie-chart path:nth-of-type(2) {
  fill: var(--slice-2-bg);
}
.pie-chart path:nth-of-type(3) {
  fill: var(--slice-3-bg);
}


/*Downloaded from https://www.codeseek.co/Hiswe/react-pie-chart-geyoxr */
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var BASE_CLASS = "pie-chart";

var PieChart = function (_React$PureComponent) {
  _inherits(PieChart, _React$PureComponent);

  function PieChart(props) {
    _classCallCheck(this, PieChart);

    return _possibleConstructorReturn(this, (PieChart.__proto__ || Object.getPrototypeOf(PieChart)).call(this, props));
  }

  _createClass(PieChart, [{
    key: "createSlices",
    value: function createSlices(slices) {
      var cumulativePercent = 0;
      return slices.map(function (percent, index) {
        // destructuring assignment sets the two variables at once
        var _PieChart$getCoordina = PieChart.getCoordinatesForPercent(cumulativePercent),
            _PieChart$getCoordina2 = _slicedToArray(_PieChart$getCoordina, 2),
            startX = _PieChart$getCoordina2[0],
            startY = _PieChart$getCoordina2[1];
        // each slice starts where the last slice ended, so keep a cumulative percent


        cumulativePercent = cumulativePercent + percent;

        var _PieChart$getCoordina3 = PieChart.getCoordinatesForPercent(cumulativePercent),
            _PieChart$getCoordina4 = _slicedToArray(_PieChart$getCoordina3, 2),
            endX = _PieChart$getCoordina4[0],
            endY = _PieChart$getCoordina4[1];
        // if the slice is more than 50%, take the large arc (the long way around)


        var largeArcFlag = percent > .5 ? 1 : 0;
        // some SVG path here
        // • M = Move
        // • A = Arc
        // • L = Line
        var pathData = ["M " + startX + " " + startY, "A 1 1 0 " + largeArcFlag + " 1 " + endX + " " + endY, "L 0 0"].join(" ");
        return React.createElement("path", { key: index, d: pathData });
      });
    }
  }, {
    key: "render",
    value: function render() {
      var slices = this.props.slices;

      this.cumulativePercent = 0;
      return React.createElement(
        "div",
        { className: BASE_CLASS },
        React.createElement(
          "p",
          { className: BASE_CLASS + "__title" },
          "React Pie Chart"
        ),
        React.createElement(
          "svg",
          { viewBox: "-1 -1 2 2", className: BASE_CLASS + "__pie" },
          React.createElement(
            "defs",
            null,
            React.createElement(
              "mask",
              { id: "pie-mask" },
              React.createElement("rect", { fill: "white", x: "-1", y: "-1", width: "2", height: "2" }),
              React.createElement("circle", { fill: "black", cx: "0", cy: "0", r: ".65" })
            )
          ),
          React.createElement(
            "g",
            { mask: "url(#pie-mask)" },
            React.createElement("circle", { className: BASE_CLASS + "__pie_bg", cx: "0", cy: "0", r: "1" }),
            this.createSlices(slices)
          )
        )
      );
    }
  }], [{
    key: "getCoordinatesForPercent",
    value: function getCoordinatesForPercent(percent) {
      var x = Math.cos(2 * Math.PI * percent);
      var y = Math.sin(2 * Math.PI * percent);
      return [x, y];
    }
  }]);

  return PieChart;
}(React.PureComponent);

var rSlices = [0.1, 0.65, 0.2];

function Demo() {
  return React.createElement(
    React.Fragment,
    null,
    React.createElement(PieChart, { slices: rSlices }),
    React.createElement(
      "p",
      null,
      "based on ",
      React.createElement(
        "a",
        { href: "https://hackernoon.com/a-simple-pie-chart-in-svg-dbdd653b6936", target: "_blank" },
        "a simple pie chart in svg"
      ),
      React.createElement("br", null),
      "by ",
      React.createElement(
        "a",
        { href: "https://hackernoon.com/@david.gilbertson", target: "_blank" },
        "david gilbertson"
      )
    )
  );
}

ReactDOM.render(React.createElement(Demo, null), document.getElementById('root'));

Comments