react-chartjs-2 - updating/resetting the chart #11670
Replies: 1 comment
-
I've solved the problem by moving all the plugins outside conditionals and register/unregister them conditionally, plus inserting key={data.chartType} for React to detect changes :) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
With an object "data" sent from backend I constructed three different data: {[datasets]} and options {} under three conditionals defined by data.chartType from backend. Each conditional also have some custom plugins (globally registered).
But if i already have on screen a chart defined by let's say condition1 then doing the above renders the chart defined in condition2 and it doesn't remove the previous chart (i see some elements from the chart/condition1).
Is there any way to reset/update the chart when new data or data.chartType is received? I think part of the problem is how I registered the custom plugins.
import './ScatterChart.scss'
import { Scatter } from 'react-chartjs-2';
import ChartDataLabels from 'chartjs-plugin-datalabels';
import { Chart, LineElement, CategoryScale, LinearScale, PointElement, Title, SubTitle, Legend } from "chart.js";
Chart.register(LineElement, CategoryScale, LinearScale, PointElement, Title, SubTitle, Legend, ChartDataLabels);
const ScatterChart = ({ data, htmlAction, commonClass = 'main-component' }) => {
if (data.chartType === "condition1") {
data is changed to prepare the following:
chartData.datasets = [...]
chartOptions = {...}
arrowPlugin1...
Chart.register(arrowPlugin1)
axisLabelsPlugin1...
Chart.register(axisLabelsPlugin1)
}
if (data.chartType === "condition2") {
data is changed to prepare the following:
chartData.datasets = [...]
chartOptions = {...}
arrowPlugin2...
Chart.register(arrowPlugin2)
axisLabelsPlugin1...
Chart.register(axisLabelsPlugin2)
}
if (data.chartType === "condition3")
.... etc.
};
export default ScatterChart;
Beta Was this translation helpful? Give feedback.
All reactions