This is an example of using ReactJs to render a force directed network graph. D3 performs all the positional calculations for each node and React handles rendering.
Created
January 26, 2016 05:58
-
-
Save helmutkian/437f9219395c68cf26b5 to your computer and use it in GitHub Desktop.
React + D3 Force Layout
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/react/0.14.3/react.min.js"></script> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script> | |
</head> | |
<body> | |
<div id="content"></div> | |
<script type="text/jsx"> | |
var size = 1000; | |
var height = 500; | |
var width = 960; | |
var charge = -0.3; | |
var data = d3.range(size).map(function(){ | |
return {r: Math.floor(Math.random() * 8 + 2)}; | |
}); | |
var start = new Date(); | |
var time = 0; | |
var ticks = 0; | |
var force = d3.layout.force() | |
.size([width, height]) | |
.nodes(data) | |
.charge(function(d){ | |
return d.r * d.r * charge; | |
}); | |
var Circles = React.createClass({ | |
render: function () { | |
var circles = this.props.data.map(function (d, i) { | |
return <circle cx={ d.x } cy={ d.y } r={ d.r } fill="steelblue" key={ i } /> | |
}); | |
return ( | |
<g>{ circles }</g> | |
); | |
} | |
}); | |
var Vis = React.createClass({ | |
getInitialState: function () { | |
return { data: data }; | |
}, | |
componentDidMount: function () { | |
var component = this; | |
force.on('tick', function () { | |
component.setState({ data: data }); | |
ticks++; | |
}); | |
force.start(); | |
force.on('end', function () { | |
var totalTime = new Date() - start; | |
console.log('Total Time:', totalTime); | |
console.log('Render Time:', time); | |
console.log('Ticks:', ticks); | |
console.log('Average Time:', totalTime / ticks); | |
}); | |
}, | |
componentWillUpdate: function () { | |
this.renderStart = new Date(); | |
}, | |
componentDidUpdate: function () { | |
time += new Date() - this.renderStart; | |
}, | |
render: function () { | |
return ( | |
<svg height={ height } width={ width }> | |
<Circles data={ this.state.data } /> | |
</svg> | |
); | |
} | |
}); | |
React.render(<Vis />, document.getElementById('content')); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment