From 91a3a4fcd5f6afb71e75fd216e5201094fbfce11 Mon Sep 17 00:00:00 2001 From: jefffriesen Date: Sun, 15 Feb 2015 17:37:23 -0700 Subject: [PATCH] all chart types update with new data passed in --- README.md | 2 +- lib/core.js | 36 ++++++++++++++++++++++++++++++++++-- 2 files changed, 35 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2147854..6b479dc 100644 --- a/README.md +++ b/README.md @@ -35,7 +35,7 @@ var MyComponent = React.createClass({ * ```data``` represents the chart data (see [chart.js](http://www.chartjs.org/) for details) * ```options``` represents the chart options (see [chart.js](http://www.chartjs.org/) for details) * all other parameters will be passed through to the ```canvas``` element - +* if data passed into the component changes, points will animate between values using chart.js' ```.update()```. If you want the chart destroyed and redrawn on every change, pass in ```redraw``` as a prop. For example `````` ### Other React projects that may interest you diff --git a/lib/core.js b/lib/core.js index cd43294..d54aba6 100644 --- a/lib/core.js +++ b/lib/core.js @@ -34,8 +34,13 @@ module.exports = { classData.componentWillReceiveProps = function(nextProps) { var chart = this.state.chart; - chart.destroy(); - this.initializeChart(nextProps); + if (this.props.redraw) { + chart.destroy(); + this.initializeChart(nextProps); + } else { + updatePoints(nextProps, chart); + chart.update(); + } }; classData.initializeChart = function(nextProps) { @@ -58,3 +63,30 @@ module.exports = { return React.createClass(classData); } }; + +var dataKeys = { + 'Line': 'points', + 'Radar': 'points', + 'Bar': 'bars' +}; + +var updatePoints = function(nextProps, chart) { + var name = chart.name; + + if (name === 'PolarArea' || name === 'Pie') { + nextProps.data.forEach(function(segment, segmentIndex) { + chart.segments[segmentIndex].value = segment.value; + }); + } else { + var dataKey = dataKeys[name]; + nextProps.data.datasets.forEach(function(set, setIndex) { + set.data.forEach(function(val, pointIndex) { + chart.datasets[setIndex][dataKey][pointIndex].value = val; + }); + }); + } +}; + + + +