Skip to content

Instantly share code, notes, and snippets.

@vsaarinen
Created August 30, 2017 13:58
Show Gist options
  • Save vsaarinen/a976f7b9248969dbf78deadac53331c9 to your computer and use it in GitHub Desktop.
Save vsaarinen/a976f7b9248969dbf78deadac53331c9 to your computer and use it in GitHub Desktop.
Combining React and D3 by letting React manage the DOM
import { scaleLinear } from 'd3-scale';
import * as React from 'react';
interface Props {
data: number[];
width: number;
height: number;
}
export default function BarChart({ width, height, data }: Props) {
const yScale = scaleLinear()
.domain([0, Math.max(...data)])
.rangeRound([height, 0]);
const barWidth = Math.floor(width / data.length);
return (
<svg width={width} height={height}>
{data.map((d, i) =>
<rect
key={i}
x={i * barWidth}
y={yScale(d)}
width={barWidth - 1}
height={height - yScale(d)}
/>,
)}
</svg>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment