Last active
December 10, 2016 19:53
-
-
Save caspg/9fe85702304207d09ee9bd4cdeacfe87 to your computer and use it in GitHub Desktop.
This file contains 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
import React, { Component } from 'react' | |
export default ChartComponent => ( | |
class ResponsiveChart extends Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
containerWidth: null, | |
} | |
this.fitParentContainer = this.fitParentContainer.bind(this) | |
} | |
componentDidMount() { | |
this.fitParentContainer() | |
window.addEventListener('resize', this.fitParentContainer) | |
} | |
componentWillUnmount() { | |
window.removeEventListener('resize', this.fitParentContainer) | |
} | |
fitParentContainer() { | |
const { containerWidth } = this.state | |
const currentContainerWidth = this.chartContainer | |
.getBoundingClientRect().width | |
const shouldResize = containerWidth !== currentContainerWidth | |
if (shouldResize) { | |
this.setState({ | |
containerWidth: currentContainerWidth, | |
}) | |
} | |
} | |
renderChart() { | |
const parentWidth = this.state.containerWidth | |
return ( | |
<ChartComponent {...this.props} parentWidth={parentWidth} /> | |
) | |
} | |
render() { | |
const { containerWidth } = this.state | |
const shouldRenderChart = containerWidth !== null | |
return ( | |
<div | |
ref={(el) => { this.chartContainer = el }} | |
className="Responsive-wrapper" | |
> | |
{shouldRenderChart && this.renderChart()} | |
</div> | |
) | |
} | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment