How to use d3 with reactJS / nextJS?

Viewed 4612

I would like to add a d3 chart, following the tutorials but nothing happens at all. i'm actually not sure if useEffect() is at the good "timing", if I should use componentDidMount, or if it's just not the good way to add in the element... Seems like I'm missing something here!

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

function drawChart() {
  const data = [12, 5, 6, 6, 9, 10];
  const h = 100;
  const w = 100;
  const svg = d3.select("body")
    .append("svg")
    .attr("width", w)
    .attr("height", h)
    .style("margin-left", 100);
                  
    svg.selectAll("rect")
      .data(data)
      .enter()
      .append("rect")
      .attr("x", (d, i) => i * 70)
      .attr("y", (d, i) => h - 10 * d)
      .attr("width", 65)
      .attr("height", (d, i) => d * 10)
      .attr("fill", "green")
}


const chart: React.FunctionComponent = () => {
  useEffect(() => {
    drawChart();
  }, []);
  
  return (
    <div>
    </div>
  );
};
export default chart;
1 Answers

What can be a source of bugs in this example is that d3 is appending the SVG to the body, which is completely outside of the React DOM.

A better approach could be to add the SVG in the JSX, and use the reference (useRef in hooks) to tell D3 where the chart must be rendered:

import * as React from "react";
import * as d3 from "d3";

function drawChart(svgRef: React.RefObject<SVGSVGElement>) {
  const data = [12, 5, 6, 6, 9, 10];
  const h = 120;
  const w = 250;
  const svg = d3.select(svgRef.current);

  svg
    .attr("width", w)
    .attr("height", h)
    .style("margin-top", 50)
    .style("margin-left", 50);

  svg
    .selectAll("rect")
    .data(data)
    .enter()
    .append("rect")
    .attr("x", (d, i) => i * 40)
    .attr("y", (d, i) => h - 10 * d)
    .attr("width", 20)
    .attr("height", (d, i) => d * 10)
    .attr("fill", "steelblue");
}

const Chart: React.FunctionComponent = () => {
  const svg = React.useRef<SVGSVGElement>(null);

  React.useEffect(() => {
    drawChart(svg);
  }, [svg]);

  return (
    <div id="chart">
      <svg ref={svg} />
    </div>
  );
};

export default Chart;

Here is a codePen for the example

Related