Using D3js and React Together

Dustin Morris
Oct 31, 2020

How do you manipulate the DOM with React in full control?

D3js is a powerful SVG creating and manipulation tool created by Mike Bostock. Here is a link to just some of the visualizations possible with the tool https://observablehq.com/@d3/gallery. Your imagination is your limit.

React is an open source framework developed and maintained by Facebook. React monitors changes to the state of the application to optimize rendering.

However, React can not do its job properly when another source is manipulating the DOM such as D3js. How do you make the two cooperate?

I am making a spinning wheel to randomly selected names (or whatever the user inputs) in a friendly way. The project isn’t complete but you can contribute to this open source project at https://github.com/dwmorris11/spinnerWheel and view the currently loaded web application here: http://spinner.westus2.azurecontainer.io/

In the spinning wheel project, I integrated D3js and React by creating an SVG node in my render method and passed the reference to that node to the D3js function that manipulates the SVG node.

render() and createBarChart() methods in the BarChart React.Component Class

The createBartChart() calls the graph function that is purely D3js. If you go to the Observable link I provided earlier you will recognize the code for the horizontal bar chart slightly modified for my use case. Also note that instead of returning the svg.node() we are just manipulating the node passed into the graph function. React will then perform the render instead of D3js.

Creating a horizontal bar chart in D3js with React performing the actual mounting and rendering

There are other ways to make D3js and React play together. But if you don’t want to use additional third party tools, this was my solution.

--

--