Chartjs-Pass custom labels as an array to Chart JS Tool tip

0👍

Instead of using an array, I would suggest you to use an object instead (similar to a map behavior), in that way I think it will make more sense.

const days = {
  Monday: "Example description for monday",
  Tuesday: "Example description for tueday",
  Wednesday: "Example description for wednesday",
  Thursday: "Example description for thursday",
  Friday: "Example description for friday",
  Saturday: "Example description for saturday",
  Sunday: "Example description for sunday"
};

In your labels key in your chart options, you can use Object.keys() to get all keys as the label. And the key value is the description of your tooltip.

data: {
  labels: Object.keys(days),
  datasets: [
    {
      maxBarThickness: 1,
      label: "Visitors",
      backgroundColor: [
        "#D1E6E9",
        "#566573",
        "#201736",
        "#707B7C",
        "#4A235A"
      ],
      data: [5, 4, 6, 7]
    },
  ],
},
...
tooltips: {
  callbacks: {
    beforeTitle: tooltip => days[tooltip[0].yLabel],
  },
},

Everything together

const days = {
  Monday: "Example description for monday",
  Tuesday: "Example description for tueday",
  Wednesday: "Example description for wednesday",
  Thursday: "Example description for thursday",
  Friday: "Example description for friday",
  Saturday: "Example description for saturday",
  Sunday: "Example description for sunday"
};

new Chart(document.getElementById("eventVisitors"), {
  type: "horizontalBar",
  data: {
    labels: Object.keys(days),
    datasets: [
      {
        maxBarThickness: 1,
        label: "Visitors",
        backgroundColor: [
          "#D1E6E9",
          "#566573",
          "#201736",
          "#707B7C",
          "#4A235A"
        ],
        data: [5, 4, 6, 7],
      },
    ],
  },
  options: {
    legend: { display: false },
    title: {
      display: false,
      text: "Visitor Origin"
    },
    tooltips: {
      callbacks: {
        beforeTitle: tooltip => days[tooltip[0].yLabel],
      },
    },
    scales: {
      xAxes: [
        {
          gridLines: {
            drawBorder: true,
            display: false
          },
          ticks: {
            fontSize: 16,
            beginAtZero: true,
            callback: function(value) {
              if (value % 1 === 0) {
                return value;
              }
            },
          },
        },
      ],
      yAxes: [
        {
          gridLines: {
            drawBorder: true,
            display: false
          },
          ticks: {
            fontSize: 16
          },
        },
      ],
    },
  },
});

Leave a comment