top of page

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(() => {".target").style("stroke-width", 5);
  }, []);
  return (
    <div className="App">
          style={{ fill: "green" }}

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.bottom;
  const x = d3.scaleTime().range([0, width]);
  const y = d3.scaleLinear().range([height, 0]);
  const valueLine = d3.line()
    .x((d) => { return x(; })
    .y((d) => { return y(d.close); });
  const svg ="body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + + margin.bottom)
    .attr("transform", `translate(${margin.left}, ${})`);
  let data = await d3.csv(require("./data.csv"))
  data.forEach((d) => { = parseTime(;
    d.close = +d.close;
  data = data.sort((a, b) => -
  x.domain(d3.extent(data, (d) => { return; }));
  y.domain([0, d3.max(data, (d) => { return d.close; })]);
    .attr("class", "line")
    .attr("d", valueLine);
    .attr("transform", `translate(0, ${height})`)
export default function App() {
  useEffect(() => {
  }, []);
  return (
            .line {
            fill: none;
             stroke: steelblue;
            stroke-width: 2px;

With this, we’ll see a line instead of a filled shape.


Great. See how easily we can create graphics with D3.js. It works well with React apps and can be integrated with no extra work.

Contact us at for more information.

79 views0 comments


bottom of page