D3 Choropleth in React App

tl;dr: I’m sharing an example of how to use D3 in a React app. See below for links.

I finished up the FCC curriculum a while ago and have been doing further prep work before I start applying to jobs. Part of what I’ve been working on is setting up my portfolio site and posting project work. I just recently got around to migrating some of my D3 work from Codepen I had forgotten about to a standalone instance/ app on my site.

I hadn’t seen a ton of buzz around using D3 within React, so I figured I’d share my code. This was an interesting little project given that D3 and React each manipulate the DOM in different ways, so getting them to play nicely together can be a little bit of a challenge. I also didn’t want to use any other third-party dependencies - stuck to vanilla D3 and React so I could get the workflow and structure down for future projects and use each to their full strengths.

After experimenting with numerous methods, I settled on just creating a small component (Map.jsx) that exposes a single div within my React code. Within that component I reference a standalone JavaScript helper file (helper.js), where all of my D3 code exists. No JSX, just JS as you would expect in any standalone D3 project. All network requests to grab data are handled in the componentDidMount lifecycle method and then that data is passed to the draw() function contained in my helper file.

Here’s a link to the live demo: https://d3-choropleth.jeffbloom.io/

Here’s a link to the Github repo (still working through some refactoring): https://github.com/bloo0178/d3-choropleth

Just wanted to share in case anybody was curious how to tie the two together. Thanks for reading!

1 Like