Skip to content

Instantly share code, notes, and snippets.

@swallentin
Created August 20, 2016 07:50
Show Gist options
  • Save swallentin/adeda79c9315add93db8e64ba6d7aa0c to your computer and use it in GitHub Desktop.
Save swallentin/adeda79c9315add93db8e64ba6d7aa0c to your computer and use it in GitHub Desktop.
D3 Responsive Chart Container
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import d3 from 'd3';
class ResponsiveChartContainer extends Component {
static defaultProps = {
width: '100%',
height: 300,
margin: {top: 0, right: 0, bottom: 0, left: 0}
}
constructor (props) {
super(props)
this.state = {
parentWidth: 0
}
this.onWindowResize = this.onWindowResize.bind(this);
}
componentDidMount () {
window.addEventListener('resize', this.onWindowResize);
this.onWindowResize();
}
componentWillUnmount () {
window.removeEventListener('resize', this.onWindowResize);
}
onWindowResize (e) {
this.setState({
width: ReactDOM.findDOMNode(this).offsetWidth
})
}
render () {
const {width} = this.state;
const {height, margin} = this.props;
const w = width - margin.left + margin.right;
const h = height - (margin.top + margin.bottom);
const xScale = d3.scaleLinear().range([0, w]);
const yScale = d3.scaleLinear().range([h, 0]);
return (
<svg width={width} height={height} margin={margin}>
{React.cloneElement(this.props.children, {xScale: xScale, yScale: yScale})}
</svg>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment