D3 and React Resources

There are a variety of ways to have D3 and React interact since they both modify the DOM. Generally the recommended approach is “use useRef to access a React-rendered DOM element, and then put the D3 logic in a useEffect“.

useEffect(() => {
   if (svgRef.current) {
      const nodeJoin = d3.select(svgRef.current)
                         .selectAll(".node")
                         .data(data.nodes);

      nodeJoin.exit().remove();
      nodeJoin.enter().append("circle")...

      // Update data
      nodeJoin.attr("cx", d => d.x).attr("cy", d => d.y);
   }
}, [data, svgRef])

Blog Posts

https://wattenberger.com/blog/react-and-d3

Libraries

https://airbnb.io/visx/

Youtube Videos

Github Repositories

https://github.com/TheeMattOliver/d3-react-census-us-population-bar

Arrowhead SVG scaling

When using SVG definitions to add arrowheads to your line in D3, use markerUnits and set a stroke-width attribute if you don’t want the arrowhead to scale with the line.

Static arrowhead:

svg.append('defs').append('marker')
        .attr("id", "arrowhead")
        .attr("markerUnits","userSpaceOnUse")
        .attr("viewBox", "0 -5 10 10")
        .attr("refX",32) 
        .attr("refY", -1)
        .attr("markerWidth", 12)
        .attr("markerHeight", 12)
        .attr("orient", "auto")
        .attr("stroke-width",2)
        .append("path")
        .attr("d", "M0,-5L10,0L0,5")
        .attr('fill','rgb(104, 104, 104)');

Scaling Arrowhead definition

svg.append('defs').append('marker')
        .attr("id",'arrowhead')
        .attr('viewBox','-0 -5 10 10') 
        .attr('refX', 32)
        .attr('refY', -1)
        .attr('orient','auto')
        .attr('markerWidth',12)
        .attr('markerHeight',12)
        .attr('xoverflow','visible')
        .append('svg:path')
        .attr('d', 'M 0,-5 L 10 ,0 L 0,5')
        .attr('fill', 'rgb(104, 104, 104)')
 

Thanks to the D3 slack and Eric S for these tips

d3 currency

To have d3 print currency symbols, we use d3.format('$.2f')(value) .  This natively produces a dollar sign because the locale is typically set to en-US, but it’s more helpful to think of the $ in the format as include a currency symbol.  Therefore if you want to produce a pound symbol (£), then you would change the locale to en-GB and d3.format would output the £instead.

Thanks to @Kevin James on the d3-slack.