I have a react component that receives two inputs: data and normalizer.
<ChartInterface
normalizer={[10, 10, 10, 10]}
data={[
{ name: "lineA", data: [2, 1, 1, 2] },
{ name: "lineB", data: [1, 0, 3, 0] }
]}
/>
The ChartInterface component should render a checkbox and a chart; when the checkbox is not checked, it should render just a chart with the data, which works fine; if the checkbox is checked, the component should divide all the data arrays by the normalizerarray, which i have written functions to do so.
However, the problem is when I repeatedly check and uncheck this checkbox, the data keeps being divided by the array over and over again.
This problem only occurs when I add the <HighchartsReact options={chartOptions} highcharts={Highcharts} /> Component, if i comment it out and just print the chartOptions.lineData the checkbox works as intended. (checking the checkbox shows normalized data, and unchecking shows the original data as it was given as a prop)
The ChartInterface component:
const ChartInterface = (props) => {
// state for checkbox if chart needs to be normalized or not
const [isNormalized, setIsNormalized] = useState(false);
//divides one array by another, element-wise
function normalize(a, b) {
return a.map(function (x, idx) {
return x / b[idx];
});
}
// get data for lines
let lineData = props.data;
//if normalized is checked, normalize the data
if (isNormalized) {
lineData = lineData.map((line) => {
return {
name: line.name,
data: normalize(line.data, props.normalizer)
};
});
}
// Chartoptions for highcharts, here we add the line data
const chartOptions = {
chart: { type: "area" },
xAxis: {
type: "category",
crosshair: true
},
plotOptions: {
area: {
stacking: "normal",
lineWidth: 1
}
},
series: lineData
};
return (
<>
<input
type="checkbox"
checked={isNormalized}
onChange={(e) => setIsNormalized(e.target.checked)}
/>
Normalise the data ?
{<HighchartsReact options={chartOptions} highcharts={Highcharts} />}
{JSON.stringify(lineData)}
</>
);
};
I have also made a code sandbox example where you can easily see by checking and unchecking the checkbox what the problem is: codesandbox demo of problem Thank you for your help