Be the first user to complete this post
|
Add to List |
Render a d3js Tree as a React Component
Since we are going to use the react-webpack-setup project, we will be conveniently using npm and require in our front end code.
The packages
D3 is available as a package from npm, so you can add it to your project by running
npm install d3
The components
The next part of the code shows the main Page.jsx file that acts as the master component of the page. Since this is just an example, we will be creating the treeData object in this component and passing it down to the D3Tree component.
js/components/index/Page.jsx
/**
* @jsx React.DOM
*/
var React = require('react'),
D3Tree = require('./D3Tree'),
treeData = [
{
"name": "Top Level",
"parent": "null",
"children": [
{
"name": "Level 2: A",
"parent": "Top Level",
"children": [
{
"name": "Son of A",
"parent": "Level 2: A"
},
{
"name": "Daughter of A",
"parent": "Level 2: A"
}
]
},
{
"name": "Level 2: B",
"parent": "Top Level"
}
]
}
];
var Page = React.createClass({
render: function() {
return (
<div>
<D3Tree treeData={treeData} />
</div>
);
}
});
module.exports = Page;
/**
* @jsx React.DOM
*/
var React = require('react'),
d3 = require('d3');
var D3Tree = React.createClass({
componentDidMount: function(){
var mountNode = this.getDOMNode();
// Render the tree usng d3 after first component mount
renderTree(this.props.treeData, mountNode);
},
shouldComponentUpdate: function(nextProps, nextState){
// Delegate rendering the tree to a d3 function on prop change
renderTree(this.props.treeData, this.getDOMNode());
// Do not allow react to render the component on prop change
return false;
},
render: function() {
// Render a blank svg node
return (
<svg></svg>
);
}
});
var renderTree = function(treeData, svgDomNode) {
// Add the javascript code that renders the tree from
// http://bl.ocks.org/d3noob/8329404
// And replace the line that reads
// var svg = d3.select("body").append("svg")
// with
// var svg = d3.select(svgDomNode)
}
That said, you are now ready for showtime. To see the working example for yourself, download the branch - react-backbone-model from our repository and run the following commands on your terminal.
sudo npm install -g grunt-cli
npm install
npm run dev
localhost:3000/index.html
in your browser and you should be able to see a tree rendered using d3 and react.
Also Read:
- Using React with Backbone Models
- combineReducers in reduxjs explained
- Pass props to the handler component in react-router
- Creating an Animated Ring or Pie chart in d3js
- Using d3js to draw a bar chart with an axis and some basic transitions