Skip to content

React Code

Andrew Burke edited this page Jun 2, 2016 · 2 revisions

React Code

In this file require in the component from our library. Use this component and pass in the node as state.

import React from 'react';
import node from './diagram';
import rd3 from 'react-d3-library';
const RD3Component = rd3.Component;

module.exports = React.createClass({

  getInitialState: function() {
    return {d3: ''}
  },

  componentDidMount: function() {
    this.setState({d3: node});
  },

  render: function() {
    return (
      <div>
        <RD3Component data={this.state.d3} />
      </div>
    )
  }
});

This will work for all static D3 code. It will also work for event listeners as long as the callback functions inside those event listeners don’t refer to variables in your d3 code that represent elements on the DOM. IF YOUR CALLBACK FUNCTIONS DO REFER DOM ELEMENTS YOU HAVE TO RESELECT THOSE ELEMENTS IN THE CALLBACK. This is because React is creating different elements on the DOM than the ones inside your D3 code. These elements are only used to get the data React needs to create the elements. Below is an example where elements are reselected inside the callback:

	svg.append("rect")
	    .attr("width", width)
	    .attr("height", height)
	    .style("fill", "none")
	    .style("pointer-events", "all")
	    .call(d3.zoom()
	        .scaleExtent([1 / 2, 4])
	        .on("zoom", zoomed));

	function zoomed() {
		//reselect DOM elements if they are in an event listener
	  var body = d3.select('body');
	  var circle = body.selectAll('circle');
	  var transform = d3.event.transform;
	  circle.attr("transform", function(d) {
	    return "translate(" + transform.applyX(d[0]) + "," + transform.applyY(d[1]) + ")";
	  });
	}

D3 code with functionality

Clone this wiki locally