Skip to content

Instantly share code, notes, and snippets.

@vsaarinen
Created August 30, 2017 13:44
Show Gist options
  • Save vsaarinen/d52020ac60244689f688d1fcf06e0df6 to your computer and use it in GitHub Desktop.
Save vsaarinen/d52020ac60244689f688d1fcf06e0df6 to your computer and use it in GitHub Desktop.
Combining React and D3 by letting D3 manage the DOM
import { select } from 'd3-selection';
import * as React from 'react';
interface Props {
data: number[];
width: number;
height: number;
}
export default class BarChart extends React.Component<Props> {
private svgRef?: SVGElement | null;
public componentDidMount() {
this.drawChart(this.props.data);
}
public componentWillReceiveProps(nextProps: Props) {
if (nextProps.data !== this.props.data) {
this.drawChart(nextProps.data);
}
}
private drawChart(data: number[]) {
const svg = select(this.svgRef!);
/* ...Draw the chart with D3... */
}
public render() {
const { width, height } = this.props;
return (
<svg width={width} height={height} ref={ref => (this.svgRef = ref)} />
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment