Last active
February 9, 2018 16:04
-
-
Save AubreyHewes/6aceb2bfb1b201512506dfb8b568d0ab to your computer and use it in GitHub Desktop.
ReactChartJS.js based on @MatthewHerbst @ https://github.com/reactjs/react-chartjs/issues/112
This file contains hidden or 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'; | |
import PropTypes from 'prop-types'; | |
import ChartJS from 'chart.js'; | |
/** | |
* React Wrapper Component for ChartJS charts | |
* Based on comment by @MatthewHerbst @https://github.com/reactjs/react-chartjs/issues/112 | |
* | |
* For chart documentation see @see http://www.chartjs.org/docs/latest | |
*/ | |
class ReactChartJS extends Component { | |
static propTypes = { | |
height: PropTypes.number, | |
width: PropTypes.number, | |
options: PropTypes.shape({ | |
scales: PropTypes.any, | |
animation: PropTypes.any, | |
}), | |
type: PropTypes.oneOf(['line', 'bar', 'radar', 'doughnut', 'pie', 'polarArea', 'bubble', 'scatter']).isRequired, | |
data: PropTypes.shape({ | |
labels: PropTypes.array, | |
datasets: PropTypes.arrayOf(PropTypes.shape({ | |
data: PropTypes.array, | |
})) | |
}).isRequired | |
}; | |
static defaultProps = { | |
options: {}, | |
width: 600, | |
height: 400, | |
}; | |
componentDidMount() { | |
if (this.props.type) { | |
this.chart = new ChartJS(this.canvasEl, { | |
type: this.props.type, | |
data: this.props.data, | |
options: this.props.options | |
}); | |
} | |
} | |
componentDidUpdate() { | |
if (this.chart) { | |
this.chart.data.datasets = this.props.data.datasets; | |
this.chart.data.labels = this.props.data.labels; | |
//this.chart.options = this.props.options; // hm this borks it | |
this.chart.update(); | |
} | |
} | |
componentWillUnmount() { | |
if (this.chart) { | |
this.chart.destroy(); | |
} | |
} | |
setRef = (el) => { | |
this.canvasEl = el; | |
}; | |
render() { | |
return ( | |
<canvas ref={this.setRef} height={this.props.height} width={this.props.width} /> | |
); | |
} | |
} | |
export default ReactChartJS; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment