Skip to content

Instantly share code, notes, and snippets.

@briandeheus
Created April 1, 2020 09:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save briandeheus/f8957c3b6c148b3aaea3de690210bb69 to your computer and use it in GitHub Desktop.
Save briandeheus/f8957c3b6c148b3aaea3de690210bb69 to your computer and use it in GitHub Desktop.
Sparkchart for React
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