Created
August 30, 2016 04:07
-
-
Save antimatter15/60c28cf1efb57ce0a30af76303ff0cdd to your computer and use it in GitHub Desktop.
React D3 Graph
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
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import './index.css'; | |
import { forceSimulation, forceLink, forceCenter, forceManyBody } from 'd3-force'; | |
class GraphNode extends React.Component { | |
render(){ | |
var node = this.props.node; | |
return <circle cx={node.x} cy={node.y} r={node.group + 5} /> | |
} | |
} | |
class Graph extends React.Component { | |
render(){ | |
return <svg width={innerWidth} height={innerHeight} >{ | |
this.props.nodes | |
.filter(node => node.x > 0 && node.y > 0 && node.x < innerWidth && node.y < innerHeight) | |
.map(node => <GraphNode node={node} key={node.id} />) | |
}</svg> | |
} | |
} | |
// var graph = require('./miserables.json') | |
var graph = { nodes: [], links: [] } | |
for(var i = 0; i < 10000; i++){ | |
graph.nodes.push({ | |
id: i, | |
group: 5, | |
x: (Math.random() - 0.5) * 1e4, | |
y: (Math.random() - 0.5) * 1e4 | |
}) | |
} | |
for(var i = 0; i < 100; i++){ | |
graph.links.push({ | |
source: Math.floor(Math.random() * 1000), | |
target: Math.floor(Math.random() * 1000) | |
}) | |
} | |
forceSimulation() | |
.nodes(graph.nodes) | |
.force("link", forceLink(graph.links).id(d => d.id)) | |
.force("charge", forceManyBody()) | |
.force("center", forceCenter(innerWidth / 2, innerHeight / 2)) | |
.on('tick', function(){ | |
ReactDOM.render(<Graph nodes={graph.nodes} />, document.getElementById('root')); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment