1👍
This is because you have this in the setState function and this is not setting the state of anything. This should be in the componentDidMount() lifecycle function.
setState() is used to update the state of your application https://facebook.github.io/react/docs/component-api.html where as componentDidMount() will fire once your component is mounted after the initial rendering occurs and will perform the functions inside. https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount
- [Chartjs]-ChartJS bar chart fixed width for dynamic data sets
- [Chartjs]-Angular chart.js onClick is not working – how to get all elements of a bar when it is clicked on
1👍
chart.js needs a canvas to “overwrite” before it can draw its chart. You have the part where you return the canvas correct. But the function you are looking for is componentDidMount()
not setState()
. I have taken their example for pie charts and created a react class for it. It should be pretty simple to change your code to match the change.
import Chart from 'chart.js';
import React, {
Component
} from 'react';
export default class PieChart extends Component {
componentDidMount() {
debugger;
const ctx = document.getElementById("pie-chart");
const data = {
labels: [
"Red",
"Blue",
"Yellow"
],
datasets: [{
data: [300, 50, 100],
backgroundColor: [
"#FF0000",
"#0000FF",
"#FFCE56"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
};
const pieChart = new Chart(ctx, {
type: 'pie',
data: data
});
}
render() {
return (
<canvas id="pie-chart"></canvas>
);
}
}