Skip to content
Swizec Teller - a geek with a

How you can translate any random D3 example to React

You and I both know that when it's time to code some D3, the easiest approach is to find an example that does something similar, copy its code, and tweak it a bit.

But a lot of those examples are in old versions of D3, and what if you're using React or something and can't just plop code into your project like nobody's business? Here's what you do:

  1. Find the example
  2. Split it up into styling, data calc, and rendering
  3. Put those in the appropriate place for your environment

Let's do that for this example of 113th Congressional District from March 2016.

The code starts with the usual HTML declarations, loading scripts, and a block of <style> stuff. Assuming we started our React app with create-react-app, we copy all the style info into App.css. That way we never have to worry about it again.

We need styling because SVG elements are invisible by default.

Setup a component

To make our lives easy, we're going to use the D3 blackbox approach to integration React and D3. By doing it this way, we can reuse all of the example code almost without change, and we lose most of React's benefits. Great for slapping code together quickly, but I'd suggest a more structured approach for anything serious.

We need a component:

// src/CongressionalDistricts.js
import React, { Component } from 'react';
import * as topojson from 'topojson';
import * as d3 from 'd3';
class CongressionalDistricts extends Component {
state = {
usData: null,
usCongress: null
componentWillMount() {
// load data
componentDidUpdate() {
// render example D3
render() {
const { usData, usCongress } = this.state;
if (!usData || !usCongress) {
return null;
return <g ref="anchor">;
export default CongressionalDistricts;

Our CongressionalDistricts component has three parts. We're going to load data in componentWillMount, do all of our significant rendering in componentDidUpdate, and render an anchor element in render.

This approach hands control of the DOM over to D3, which is why React can't help us. Once we're inside that anchor element, it's all D3 with this approach.

Copypasta the code

Next in our example, we find the setup code.

var width = 960,
height = 600;
var projection = d3.geo
.translate([width / 2, height / 2]);
var path = d3.geo.path().projection(projection);
var svg = d3
.attr("width", width)
.attr("height", height);

This code is great, but has some problems.

It's still using var declarations, which are not encouraged in modern ES6. It also uses old D3 APIs which are going to fail when you run npm install d3 because you'll get the new D3v4 version.

On a practical level, it's setting up a new geographical projection, path generator, and creating an svg element. We can throw away the svg element creation because we're wrapping our component in svg anyway.

So we copy the projection and path setup into componentDidUpdate like this:

// src/CongressionalDistricts.js
componentDidUpdate() {
const svg =,
{ width, height } = this.props;
const projection = d3.geoAlbers()
.translate([width / 2, height / 2]);
const path = d3.geoPath(projection);
const us = this.state.usData,
congress = this.state.usCongress;

We select our anchor element and name it svg. That way we won't have to change any of the other code.

d3.geo.albersUsa becomes d3.geoAlbers and d3.geo.path becomes d3.geoPath. Same thing, simpler names. That's the general principle behind the D3v3 to D3v4 transition.

The example code assumes data is global, so we take it out of state and put it in variables. Again, so we don't have to change any of the code.

Next, the example loads its data.

.defer(d3.json, "/mbostock/raw/4090846/us.json")
.defer(d3.json, "/mbostock/raw/4090846/us-congress-113.json")

This goes in our componentWillMount method. No sense fetching data before we know the component is getting mounted. And we definitely don't want to do it on every render :)

Also, we change the URLs and download those files into our /public folder.

// src/CongressionalDistricts.js
componentWillMount() {
.defer(d3.json, "us.json")
.defer(d3.json, "us-congress-113.json")
.await((error, usData, usCongress) => {

This loads both datasets and updates component state, which triggers a re-render. Notice that with D3v4, queue is now an official part of D3. It helps us load multiple datasets sequentially.

Now for the coup-de-grace: A massive copypasta that puts all the rendering code from our example into our React component. It's messy but it works.

// src/CongressionalDistricts.js
componentDidUpdate() {
const svg =,
{ width, height } = this.props;
const projection = d3.geoAlbers()
.translate([width / 2, height / 2]);
const path = d3.geoPath(projection);
const us = this.state.usData,
congress = this.state.usCongress;
// Pure copypasta starts here
.attr("id", "land")
.attr("d", path);
.attr("id", "clip-land")
.attr("xlink:href", "#land");
.attr("class", "districts")
.attr("clip-path", "url(#clip-land)")
.data(topojson.feature(congress, congress.objects.districts).features)
.attr("d", path)
.text(function(d) { return; });
.attr("class", "district-boundaries")
.datum(topojson.mesh(congress, congress.objects.districts, function(a, b) { return a !== b && ( / 1000 | 0) === ( / 1000 | 0); }))
.attr("d", path);
.attr("class", "state-boundaries")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("d", path);

Copy all the code over, and you should get a map. It's great.

Make it better

Now here's what I'd do next. You see all those little svg.append calls? I'd change them to individual components.

That way you could have a render method that looks more like this:


I think that sort of code is easier to understand.

You can play with this example on Codepen ๐Ÿ‘‡

See the Pen 113th congressional districts D3 example moved into React by Swizec Teller (@swizec) on CodePen.

Did you enjoy this article?

Published on August 31st, 2017 in d3js, Front End, react, Technical

Learned something new?
Want to become a high value JavaScript expert?

Here's how it works ๐Ÿ‘‡

Leave your email and I'll send you an Interactive Modern JavaScript Cheatsheet ๐Ÿ“–right away. After that you'll get thoughtfully written emails every week about React, JavaScript, and your career. Lessons learned over my 20 years in the industry working with companies ranging from tiny startups to Fortune5 behemoths.

Start with an interactive cheatsheet ๐Ÿ“–

Then get thoughtful letters ๐Ÿ’Œ on mindsets, tactics, and technical skills for your career.

"Man, love your simple writing! Yours is the only email I open from marketers and only blog that I give a fuck to read & scroll till the end. And wow always take away lessons with me. Inspiring! And very relatable. ๐Ÿ‘Œ"

~ Ashish Kumar

Join over 10,000 engineers just like you already improving their JS careers with my letters, workshops, courses, and talks. โœŒ๏ธ

Have a burning question that you think I can answer?ย I don't have all of the answers, but I have some! Hit me up on twitter or book a 30min ama for in-depth help.

Ready to Stop copy pasting D3 examples and create data visualizations of your own? ย Learn how to build scalable dataviz components your whole team can understand with React for Data Visualization

Curious about Serverless and the modern backend? Check out Serverless Handbook, modern backend for the frontend engineer.

Ready to learn how it all fits together and build a modern webapp from scratch? Learn how to launch a webapp and make your first ๐Ÿ’ฐ on the side with ServerlessReact.Dev

Want to brush up on your modern JavaScript syntax?ย Check out my interactive cheatsheet:

By the way, just in case no one has told you it yet today: I love and appreciate you for who you areย โค๏ธ

Created bySwizecwith โค๏ธ