Created
April 1, 2020 09:18
-
-
Save briandeheus/f8957c3b6c148b3aaea3de690210bb69 to your computer and use it in GitHub Desktop.
Sparkchart for React
This file contains hidden or 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
const Spark = ({ | |
height = 20, | |
width = 140, | |
series = [], | |
color = "#4CAF50", | |
backgroundColor = "#37474F", | |
radius = 3, | |
padding = [4, 4] | |
}) => { | |
const max = series.reduce((p, c) => { | |
return c > p ? c : p; | |
}, series[0]); | |
if (Array.isArray(padding) === false) { | |
padding = [padding, padding]; | |
} | |
const paddingX = padding[0]; | |
const paddingY = padding[1]; | |
const maxX = width - paddingX * 2; | |
const maxY = height - paddingY * 2; | |
const yOffset = maxY / max; | |
const xOffset = maxX / (series.length - 1); | |
console.log("Max x =>", maxX, "max y =>", maxY); | |
const seriesElms = series.map((value, index) => { | |
const y = maxY - yOffset * value + paddingY; | |
const x = index * xOffset + paddingX; | |
console.log("Value =>", value, "x =>", x, "y =>", y); | |
return ( | |
<React.Fragment key={index}> | |
<circle cy={y} cx={x} r={radius} fill={color} /> | |
{series.length - 1 !== index && ( | |
<line | |
x1={x} | |
y1={y} | |
x2={(index + 1) * xOffset + paddingX} | |
y2={maxY - yOffset * series[index + 1] + paddingY} | |
stroke={color} | |
strokeWidth={1} | |
/> | |
)} | |
</React.Fragment> | |
); | |
}); | |
return ( | |
<svg | |
height={height} | |
width={width} | |
style={{ backgroundColor }} | |
className="spark-chart" | |
> | |
{seriesElms} | |
</svg> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment