Categories
JavaScript Answers

How to add custom data formatting to display on tooltip with JavaScript Chart.js?

Spread the love

Sometimes, we wanty to add custom data formatting to display on tooltip with JavaScript Chart.js.

In this article, we’ll look at how to add custom data formatting to display on tooltip with JavaScript Chart.js.

How to add custom data formatting to display on tooltip with JavaScript Chart.js?

To add custom data formatting to display on tooltip with JavaScript Chart.js, we add a label callback.

For instance, we write

const chart = new Chart(ctx, {
  type: "line",
  data: data,
  options: {
    plugins: {
      tooltip: {
        callbacks: {
          label: (context) => {
            let label = context.dataset.label || "";

            if (label) {
              label += ": ";
            }
            if (context.parsed.y !== null) {
              label += new Intl.NumberFormat("en-US", {
                style: "currency",
                currency: "USD",
              }).format(context.parsed.y);
            }
            return label;
          },
        },
      },
    },
  },
});

to set the callbacks.label property to a function that returns the label contents.

context has the chart data.

Conclusion

To add custom data formatting to display on tooltip with JavaScript Chart.js, we add a label callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *