Chartjs-Cannot read property 'length' of undefined for ChartJS when I use it inside React

0👍

Modified my code to this and got the chart displayed. I don’t know what the issue was but it could be that I hadn’t added getContext. I also created the ref outside my state.

class RadarChart extends Component {
constructor(props) {
    super(props);
}
chartRef = React.createRef();


componentDidMount () {
    const myChartRef = this.chartRef.current.getContext("2d");
    new Chart(myChartRef, {
        type: 'radar',
        data: {
            labels: this.props.labels,
            datasets: [
                {
                    label: "My Second dataset",
                    backgroundColor: "rgba(26,179,148,0.2)",
                    borderColor: "rgba(26,179,148,1)",
                    pointBackgroundColor: "rgba(26,179,148,1)",
                    pointBorderColor: "rgba(26,179,148,1)",
                    data: this.props.data
                }
            ]
        },
        options: {
            responsive: true,
            legend: {
                display: false
            }
        }
    })
}

render() {
    return <canvas ref={this.chartRef} />
}

}

Leave a comment