Chartjs-Facing problem to solve Uncaught TypeError while using chart js

0👍

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,
  });
}

Leave a comment