Pass context to options on React ChartJS 2

Viewed 2376

I'm using React ChartJS 2 to create some graphs but I want to show a label in top of them with the percentage and when I hover over them the real number. I found you can do something like this using the context on the options object.

var options = {
   tooltips: {
     enabled: false
   },
   plugins: {
     datalabels: {
       formatter: (value, ctx) => {

         let datasets = ctx.chart.data.datasets;

         if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
           let sum = datasets[0].data.reduce((a, b) => a + b, 0);
           let percentage = Math.round((value / sum) * 100) + '%';
           return percentage;
         } else {
           return percentage;
         }
       },
       color: '#fff',
     }
   }
 };

var ctx = document.getElementById("pie-chart").getContext('2d');
 var myChart = new Chart(ctx, {
   type: 'pie',
   data: {
     datasets: data
   },
   options: options
 });

Like this, but my problem is that I cannot get a way to use the context inside the options.

Does someone knows how to do this?

1 Answers

You don't have to manually pass the context to the datalabels' formatter function since the plugin takes care of this itself.

Here's a working example of the pie graph with the options specified above.

But if you want to access the chart's context in some other functions you want to pass to the options, then you can get it through the chart instance by using this.chart.ctx.

var options = {
  animation: {
    onComplete: function () {
      var chartInstance = this.chart;
      var ctx = chartInstance.ctx; // chart context
    }
  }
};
Related