React Base Fiddle (JSX)
Starting point for creating JSFiddles with React. This uses React with Addons.
by Zap Lin
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/react@latest/dist/react-with-addons.js"></script>
<script src="https://npmcdn.com/react-dom@latest/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<h3>React D3 - Donut chart</h3>
<p>to update data for chart every 2000 milliseconds</p>
<div id="container"></div>
<address><br>by <a href="https://github.com/LinZap/" target="_blank">Zap</a></address>
CSS
body{
text-align: center;
}
svg{
display: block;
margin: 0 auto;
}
JavaScript 1.7
/*
React D3 Chart Component
*/
class Donut extends React.Component{
constructor(props) {
super(props)
this.state = {data:getData()}
}
componentDidMount(){
var el = ReactDOM.findDOMNode(this)
this.mypie = new d3dount(el)
this.mypie.render(this.state.data)
// update data, every 2sec
setInterval(()=>{
this.setState( {data:getData()} )
},2000)
}
componentDidUpdate(){
this.mypie.update(this.state.data)
}
render(){
return <svg/>
}
}
/*
constructor
@el: svg tag on dom
@data: pie data
*/
class d3dount{
constructor(el){
this.svg = d3.select(el)
}
render(data){
this.width = 300
this.height = 230
this.color = d3.scale.category20()
this.pie = d3.layout.pie().sort(null)
this.arc = d3.svg.arc()
.innerRadius(this.height/2-30)
.outerRadius(this.height/2)
this.g = this.svg
.attr('width', this.width)
.attr('height', this.height)
.append('g')
.attr('transform',`translate( ${this.width/2} , ${this.height/2} )`)
this.path = this.g.selectAll('path')
.data(this.pie(data))
.enter()
.append('path')
.attr('d',this.arc)
.attr('fill', (d, i)=>this.color(i))
.each(function(d){ this._current={val:d} })
this.update(data)
}
update(data){
let enterAntiClockwise = {
startAngle: Math.PI * 2,
endAngle: Math.PI * 2
}
this.path = this.path.data(this.pie(data))
this.path.enter()
.append('path')
.attr('fill', (d, i)=>this.color(i))
.attr('d', this.arc(enterAntiClockwise))
.each(function (d) {
this._current = {
val: d,
startAngle: enterAntiClockwise.startAngle,
endAngle: enterAntiClockwise.endAngle
}
})
this.path.exit().transition().duration(750)
.attrTween('d', this.arcTweenOut(this.arc)).remove()
this.path.transition().duration(750)
.attrTween('d', this.arcTween(this.arc));
}
...