Adding Graphics to a React App with D3 — Pie Chart
Tags: react, javascript, codenewbie, beginners
Published: 2020-10-14 23:38:25

---
title: Adding Graphics to a React App with D3 — Pie Chart
published: true
date: 2020-10-13 17:56:53 UTC
tags: React,javascript,codenewbie,beginners
canonical_url: https://thewebdev.info/2020/10/13/adding-graphics-to-a-react-app-with-d3%e2%80%8a-%e2%80%8apie-chart/?utm_source=rss&utm_medium=rss&utm_campaign=adding-graphics-to-a-react-app-with-d3%25e2%2580%258a-%25e2%2580%258apie-chart
---

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**

D3 lets us add graphics to a front-end web app easily.

Vue is a popular front end web framework.

They work great together. In this article, we’ll look at how to add graphics to a Vue app with D3.

### Pie Chart

We can add a pie chart into our React app with D3.

For instance, we can write:

`public/populations.csv`

```
states,percent
California,38.00
New York,18.00
Texas,20.0

```

`src/App.js`

```
import React, { useEffect } from "react";
import * as d3 from "d3";

const createPieChart = async () => {
  const svg = d3.select("svg"),
    width = svg.attr("width"),
    height = svg.attr("height"),
    radius = Math.min(width, height) / 2;

  const g = svg
    .append("g")
    .attr("transform", `translate(${width / 2}, ${height / 2})`);

  const color = d3.scaleOrdinal(["gray", "green", "brown"]);

  const pie = d3.pie().value(function (d) {
    return d.percent;
  });

  const path = d3
    .arc()
    .outerRadius(radius - 10)
    .innerRadius(0);

  const label = d3
    .arc()
    .outerRadius(radius)
    .innerRadius(radius - 80);

  const data = await d3.csv("/populations.csv");

  const arc = g
    .selectAll(".arc")
    .data(pie(data))
    .enter()
    .append("g")
    .attr("class", "arc");

  arc
    .append("path")
    .attr("d", path)
    .attr("fill", function (d) {
      return color(d.data.states);
    });

  arc
    .append("text")
    .attr("transform", function (d) {
      return `translate(${label.centroid(d)})`;
    })
    .text(function (d) {
      return d.data.states;
    });

svg
    .append("g")
    .attr("transform", `translate(${width / 2 - 120},20)`)
    .append("text")
    .text("Top population states in the US")
    .attr("class", "title");
};

export default function App() {
  useEffect(() => {
    createPieChart();
  }, []);

  return (
    <div className="App">
      <style>{`
        .arc text {
          font: 12px arial;
          text-anchor: middle;
        }

        .arc path {
          stroke: #fff;
        }

        .title {
          fill: green;
          font-weight: italic;
        }
      `}</style>
      <svg width="600" height="400"></svg>
    </div>
  );
}

```

We put the CSV in the `public` folder so that we can read static files in our React code.

The `createPieChart` function lets us get the `svg` element.

And we set the `width` , `height` and `radius` of the pie chart.

We create the group for the pie with:

```
const g = svg
   .append("g")
   .attr("transform", `translate(${width / 2}, ${height / 2})`);

```

Then we add the colors with:

```
const color = d3.scaleOrdinal(["gray", "green", "brown"]);

```

Next, we add the pies with:

```
const pie = d3.pie().value(function(d) {
  return d.percent;
});

```

Then add the arcs for the pie with:

```
const path = d3
  .arc()
  .outerRadius(radius - 10)
  .innerRadius(0);

```

The labels are added with:

```
const label = d3
  .arc()
  .outerRadius(radius)
  .innerRadius(radius - 80);

```

Then we read the `population.csv` file with:

```
const data = await d3.csv("/populations.csv");

```

We set the lengths of the arc with:

```
const arc = g
  .selectAll(".arc")
  .data(pie(data))
  .enter()
  .append("g")
  .attr("class", "arc");

```

And we set the pie colors with:

```
arc
  .append("path")
  .attr("d", path)
  .attr("fill", function(d) {
    return color(d.data.states);
  });

```

And we set the text labels for the pies with:

```
arc
  .append("text")
  .attr("transform", function(d) {
    return `translate(${label.centroid(d)})`;
  })
  .text(function(d) {
    return d.data.states;
  });

```

Finally, we add the title of the chart with:

```
svg
  .append("g")
  .attr("transform", `translate(${width / 2 - 120},20)`)
  .append("text")
  .text("Top population states in the US")
  .attr("class", "title");

```

In `App` , we add the styles for the arc so that we can set the font and title color to what we want.

### Conclusion

We can add a pie chart easily into our React app.

The post [Adding Graphics to a React App with D3 — Pie Chart](https://thewebdev.info/2020/10/13/adding-graphics-to-a-react-app-with-d3%e2%80%8a-%e2%80%8apie-chart/) appeared first on [The Web Dev](https://thewebdev.info).