Using D3 in a React component to transition elements. Alternative implementations only with D3 and using React's TransitionGroup addon.
Last active
April 12, 2017 13:24
-
-
Save jstcki/9205257 to your computer and use it in GitHub Desktop.
Transitions with React and D3 I
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> | |
<meta charset="utf-8"> | |
<style> | |
body { | |
background: #fff; | |
} | |
.item { | |
fill: none; | |
stroke-width: 1.5; | |
} | |
</style> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script src="http://fb.me/react-0.9.0.min.js"></script> | |
<script> | |
var width = 960, | |
height = 500, | |
data = []; | |
var x = d3.scale.linear() | |
.domain([0, 1]) | |
.range([0, width]); | |
var y = d3.scale.linear() | |
.domain([0, 1]) | |
.range([150, height - 150]); | |
var r = d3.scale.sqrt() | |
.domain([0, 1]) | |
.range([0, 30]); | |
var chart = React.createClass({ | |
render: function() { | |
return React.DOM.svg({ | |
width: width, | |
height: height | |
}); | |
}, | |
componentDidUpdate: function() { | |
var item = d3.select(this.getDOMNode()).selectAll('circle') | |
.data(this.props.items, function(d) { return d.key; }); | |
item.enter().append('circle') | |
.attr('class', 'item') | |
.attr('r', function(d) { return r(d.r); }) | |
.attr('cx', function(d) { return x(d.x); }) | |
.attr('cy', 0) | |
.style('stroke', '#3E6E9C') | |
.transition().duration(1000) | |
.attr('cy', function(d) { return y(d.y); }) | |
.style('stroke', '#81E797'); | |
item.exit().filter(':not(.exiting)') // Don't select already exiting nodes | |
.classed('exiting', true) | |
.transition().duration(1000) | |
.attr('cy', height) | |
.style('stroke', '#3E6E9C') | |
.remove(); | |
} | |
}); | |
function render() { | |
React.renderComponent( | |
chart({items: data}), | |
document.body | |
); | |
} | |
var circlesCreated = 0; | |
function add() { | |
data.push({key: Date.now(), x: Math.random(), y: Math.random(), r: Math.random()}); | |
render(); | |
setTimeout(data.length < 100 ? add : remove, 5); | |
} | |
function remove() { | |
data = data.slice(1); | |
render(); | |
if (++circlesCreated === 1000) console.timeEnd('1000 circles'); | |
setTimeout(data.length > 0 ? remove : add, 5); | |
} | |
console.time('1000 circles'); | |
add(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment