Last active
May 8, 2018 23:34
-
-
Save alex-hofsteede/9a87bcad84b54d104c46e4ee47b6b040 to your computer and use it in GitHub Desktop.
Sparklines react component
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
class Sparkline extends React.Component { | |
constructor(props) { | |
super(props); | |
console.log(props) | |
this.state = { | |
values: props.values, | |
width: props.width, | |
height: props.height, | |
} | |
} | |
componentWillReceiveProps(nextProps) { | |
this.setState({ | |
values: nextProps.values | |
}); | |
} | |
render() { | |
var values = this.state.values || [0]; | |
var limits = [Math.max(0, Math.min.apply(this, values) - 1), Math.max.apply(this, values) + 1]; | |
var scale = Math.pow(10, Math.floor(Math.log10(limits[1] - limits[0]))); | |
var domain = [Math.floor(limits[0] / scale) * scale, Math.ceil(limits[1] / scale) * scale]; | |
var range = [this.state.height, 0]; | |
var step = this.state.width / Math.max(values.length - 1, 1) | |
var x = function(dx) { return dx * step; }; | |
var y = function(dy) { return ((dy - domain[0]) / (domain[1] - domain[0]) * (range[1] - range[0])) + range[0]; }; | |
var path = values.map(function (v, i) { return "L" + x(i) + "," + y(v); }).join() | |
var strokepath = "M" + path.substring(1); | |
var fillpath = "M0," + range[0] + path + "L" + this.state.width + "," + range[0] + "L0," + range[0] | |
var lastval = values.slice(-1)[0]; | |
return ( | |
<svg id="sparkline" width={this.state.width} height={this.state.height}> | |
<rect width={this.state.width} height={this.state.height} fill={'#EEE'}/> | |
<path className="sparkfill" d={fillpath}/> | |
<path className="sparkstroke" d={strokepath}/> | |
<text x={0} y={range[0]} fontFamily="Verdana" fontSize="8">{domain[0]}</text> | |
<text x={0} y={range[1]} fontFamily="Verdana" fontSize="8">{domain[1]}</text> | |
<text x={this.state.width} y={y(lastval)} fontFamily="Verdana" fontSize="8">{lastval}</text> | |
</svg> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment