Adding Graphics to a React App with D3 — Line Graph
Tags: react, javascript, codenewbie, beginners
Published: 2020-10-14 23:38:27

---
title: Adding Graphics to a React App with D3 — Line Graph
published: true
date: 2020-10-13 17:57:23 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%8aline-graph/?utm_source=rss&utm_medium=rss&utm_campaign=adding-graphics-to-a-react-app-with-d3%25e2%2580%258a-%25e2%2580%258aline-graph
---

**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.

### Line Graph

We can add a line graph into our React app with D3.

To do this, we write:

`public/data.csv`

```
year,population
2006,20
2008,25
2010,38
2012,41
2014,53
2016,26
2017,42

```

`App.js`

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

const createLineChart = async () => {
  const margin = { top: 20, right: 20, bottom: 30, left: 50 },
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

  const x = d3.scaleTime().range([0, width]);
  const y = d3.scaleLinear().range([height, 0]);

  const valueline = d3
    .line()
    .x(function (d) {
      return x(d.year);
    })
    .y(function (d) {
      return y(d.population);
    });

  const svg = d3
    .select("body")
    .append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", `translate(${margin.left}, ${margin.top})`);

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

  data.forEach(function (d) {
    d.population = +d.population;
  });

  x.domain(
    d3.extent(data, function (d) {
      return d.year;
    })
  );

  y.domain([
    0,
    d3.max(data, function (d) {
      return d.population;
    })
  ]);

  svg.append("path").data([data]).attr("class", "line").attr("d", valueline);

  svg
    .append("g")
    .attr("transform", `translate(0, ${height})`)
    .call(d3.axisBottom(x));

svg.append("g").call(d3.axisLeft(y));
};

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

  return (
    <div className="App">
      <style>{`
        .line {
          fill: none;
          stroke: green;
          stroke-width: 5px;
        }
      `}</style>
    </div>
  );
}

```

We create the `createLineChart` function to create the line chart.

First, we write:

```
const margin = {
    top: 20,
    right: 20,
    bottom: 30,
    left: 50
  },
  width = 960 - margin.left - margin.right,
  height = 500 - margin.top - margin.bottom;

```

to set the margins, width, and height of the chart.

Then we add the `x` and `y` objects to let us add the min and max values for the lines:

```
const x = d3.scaleTime().range([0, width]);
const y = d3.scaleLinear().range([height, 0])

```

Then we set the data for the `x` and `y` axes:

```
const valueline = d3
  .line()
  .x(function(d) {
    return x(d.year);
  })
  .y(function(d) {
    return y(d.population);
  });

```

Next, we add the `svg` element into our component with:

```
const svg = d3
  .select("body")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", `translate(${margin.left}, ${margin.top})`);

```

Then we read the data from the CSV with:

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

```

Then we add the `x` and `y` domains with:

```
data.forEach(function(d) {
  d.population = +d.population;
});

x.domain(
  d3.extent(data, function(d) {
    return d.year;
  })
);

y.domain([
  0,
  d3.max(data, function(d) {
    return d.population;
  })
]);

```

to return the labels for the x and y axes.

To add the line, we write:

```
svg.append("path").data([data]).attr("class", "line").attr("d", valueline);

```

We add the x-axis with:

```
svg
  .append("g")
  .attr("transform", `translate(0, ${height})`)
  .call(d3.axisBottom(x));

```

And we add the y-axis with:

```
svg.append("g").call(d3.axisLeft(y));

```

### Conclusion

We can add a line graph with D3 into our React app.

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