Skip to content

Instantly share code, notes, and snippets.

@caspg
Last active December 10, 2016 19:53
Show Gist options
  • Save caspg/9fe85702304207d09ee9bd4cdeacfe87 to your computer and use it in GitHub Desktop.
Save caspg/9fe85702304207d09ee9bd4cdeacfe87 to your computer and use it in GitHub Desktop.
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