facing problem to solve Uncaught TypeError while using chart js

Viewed 45

I have used some chart js configuration for my project but when my index page is loaded in the console it shows

Uncaught TypeError: Cannot read property 'height' of null at customchart.js:612

Since I am a newbie can anyone help me to solve this?

1 Answers

If you click the error in the console it takes you to the line of code causing the error. It's the second line shown here:

var ctxHBar = document.getElementById("horizontal_bar_chart");
ctxHBar.height = lbls.length * 12 + 15;
// further code...

The issue is because there is no #horizontal_bar_chart element in the DOM, so you cannot set its height.

You can fix the issue with a simple condition to check the element exists first.

var ctxHBar = document.getElementById("horizontal_bar_chart");
if (ctxBar) {
  ctxHBar.height = lbls.length * 12 + 15;
  Chart.defaults.global.defaultFontFamily = "Roboto";
  Chart.defaults.global.defaultFontStyle = "500";
  var myHorizBarChart = new Chart(ctxHBar, {
    type: "horizontalBar",
    data: data,
    options: options,
  });
}
Related