D3 + React Intro — Part 1: Simple D3 Pie Chart in React

Scott Hunt
principledminds
Published in
2 min readJun 8, 2018

I’ve been thinking about doing an intro series to using D3 with React, since I’m a massive fan of the library, have built cool shit with it, and have only recently been building with it in React, so I’m still learning a lot about best practices and what’s possible etc.

A Simple Example:

Since most intros start with the basics, I’ll stay true to form and, thus, let’s explore a simple pie chart to get our hands dirty.

Simple Pie Chart

Step by Step Breakdown

We start off by importing React and D3 and creating a small array with random values (I like using VERY basic data when I’m exploring new ideas (No need to get fancy when all you want is to put something on the screen).

Next, we have to build our main component. This is the component that will ultimately get exported. It’s pretty straightforward…

  1. Set height and width for your <svg>
  2. Call d3’s pie() function with the data you created above and store it in a variable
  3. Return your <g> wrapped inside the <svg> and encapsulate your child component (I called it ‘Slice’ here but you can call it whatever you want) inside the <g>.

Two things to remember: 1) offset your <g> so that it’s centered in the <svg> and 2) pass your ‘pie’ value as props to your child component.

Lastly, all we have to do is create our pie slices and we’re done!

  1. Create a variable that stores the return values of d3.arc() (Make sure to set your inner and outer radius, as well)
  2. Optional → Create an interpolator function using D3’s interpolateRgb(). It’s a super neat feature to create complex coloring on the fly (p.s. It expects a value between 0 and 1 in this case, which I’m achieving by dividing my index by the length of the pie array, less 1).
  3. In your return method, utilize the .map() function to return unique <path> elements for each value in your array. Inside the element, pass in your attributes ‘d’ and ‘fill’ and, voila!, that’s it.

Hope this was helpful.

Scott

--

--