I'm using chart.js to create a chart.
Declare data: minsu by importing Array named minsu in data.
And according to the minsu value, green if greater than 100
A conditional statement is created with a 'yellow if less than 100' for statement.
But I get an error with the for (let i =0 i < dataset.data.length; i++) syntax.
TypeError: Cannot read properties of undefined (reading 'length')
If I modify the code in the for conditional statement, it will render properly, but I do not know how to modify the code.
let minsu = ProductDetail && ProductDetail.materialsInfo.map(array => array.chartPercentage)
console.log(minsu); // Array [100, 50, 20, 60, 120]
let chartColors = {
yellow: 'rgb(244, 208, 104)',
green: '#4CC26F',
gray: '#EBEBEB'
};
const data = {
datasets: [
{
backgroundColor: [],
data: minsu,
},
],
};
console.log(data); // Array [100, 50, 20, 60, 120]
// The reference value is 100 .
let colorChangeValue = 100;
let dataset = data.datasets[0];
for (let i = 0; i < dataset.data.length; i++) {
if (dataset.data[i] > colorChangeValue) {
dataset.backgroundColor[i] = chartColors.green;
if (dataset.data[i] < 100) {
dataset.backgroundColor[i] = chartColors.gray;
}
}
if (dataset.data[i] < colorChangeValue) {
dataset.backgroundColor[i] = chartColors.yellow;
}
}