Skip to content

Instantly share code, notes, and snippets.

@AubreyHewes
Last active February 9, 2018 16:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AubreyHewes/6aceb2bfb1b201512506dfb8b568d0ab to your computer and use it in GitHub Desktop.
Save AubreyHewes/6aceb2bfb1b201512506dfb8b568d0ab to your computer and use it in GitHub Desktop.
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