How to use D3 with React components?

07 / Oct / 2016 by Mansi Arora 0 comments

D3 (Data Driven Documents) is a JS library that helps us build visualizations. It binds arbitrary data to a DOM, where the data-driven transformations can be applied to the document. It works well by mutating the DOM element, usually a root node that was placed in the HTML. You call .append (‘span’) and it inserts a <span></span> as a child of the node you selected.

Whereas, React on the other hand, builds the application through one big call stack to various render methods.
We create a tree of objects that represent the application and its state, and then React works out what DOM elements it should add, remove or mutate on your behalf.

The problem arises when we need to use both of them together. D3 needs DOM which is generated by React. Therefore, we need a fake DOM with enough methods to trick D3.

React-faux-dom supports a wide range of DOM operations. We can use the full D3 API with the help of react-faux-dom to have efficient D3 components and use React to render on the server side.

Steps to use D3 with React components

Installing :


npm install d3
npm install react-faux-dom

Importing D3 and ReactFauxDOM :

import ReactFauxDOM from "{path-to-ReactFauxDOM-js-file}"
import d3 from "{path-to-d3-js-file}"

Creating react component with empty render method:


const MyChart = React.createClass({
render () {},
});

Inside the render create a SVG using ReactFauxDOM:


var node = ReactFauxDOM.createElement('svg');

Now we have an SVG element and, we can do what ever we want to do with this SVG element using D3:


var svg = d3.select("node");
svg.append("div").html("First heading using d3 and React.")
.style("font-size","22px")
.style("color","green");

svg.append("circle")
   .style("fill", "blue")
   .attr("r", 40)
   .attr("cx", 150)
   .attr("cy", 350)
   .on("mouseover", function() {
        var myCircle = this;
        d3.select(myCircle).style("fill","red");
   })
   .on("mouseout", function() {
        var myCircle = this;
        d3.select(myCircle).style("fill","green");
 });

Once you are done with your SVG, then you just need to send it to React to render it accordingly:


return node.toReact();

And you are done!

Hope this helps!!

FOUND THIS USEFUL? SHARE IT

Leave a comment -