Create Graphs Using D3.JS with React

D3.js is one of the most useful JavaScript libraries to create graphics and charts. React is the most popular frontend web framework. In this blog entry, I would like to touch D3.js library in the React Apps.


Getting started


First, we’ll create a React project using create-react-app:

npx create-react-app d3-app
cd d3-app
npm start
npm i d3



Using D3.js v6 with the React App


We can use D3 in React app by putting the D3 code in the useEffect Hook callback. This is because we’re selecting an element with the DOM and then changing it with D3.

For example, we can write:

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

export default function App() {
  useEffect(() => {
    d3.select(".target").style("stroke-width", 5);
  }, []);
  return (
    <div className="App">
      <svg>
        <circle
          class="target"
          style={{ fill: "green" }}
          stroke="black"
          cx={50}
          cy={50}
          r={40}
        ></circle>
      </svg>
    </div>
  );
}

We get the SVG with the target class and then change the stroke-width after selecting it.


Creating graphs from data


One of the most important use cases for D3 is to create graphs from data. To do so, we can read the data from a CSV.

For example, we can read data from the data.csv file in the src folder:

In App.js, we write:


import React, { useEffect } from "react";
import * as d3 from "d3";
import "d3-time-format";
const parseTime = d3.timeParse("%d-%b-%y");
const createGraph = async () => {
  const margin = { top: 20, right: 20, bottom: 50, left: 70 },
    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]