javascriptreactjshighchartsreact-highcharts

Updating Highcharts Donut Chart Title Text on Legend Item Click in React


Using React.

There are 5 legend items which are of type 'number' and i have a 'title text'(type: number) at the center of the highcharts donut and the title text is the sum of all the items of legend. When i click on any of the legend item, the legend item disables and the donut chart updates accordingly with the legend items but the title text is not being updated as it is the summation of the legend items, the title text should be updated in such a way that the value should be -> (total value of title text - selected legend item value).

i tried with legendItemClick function but it didnt work, was wondering how to trigger the event when i click on legend item.


Solution

  • You can use the legendItemClick event callback and calculate the chart title based on point.visible property. For example:

      series: [{
        ...,
        point: {
          events: {
            legendItemClick: function() {
              const point = this;
              const chart = point.series.chart;
              let value = point.series.points.reduce(
                (acc, p) => {
                  if (point !== p && p.visible) {
                    return acc + p.y;
                  }
                  return acc;
                }, 0
              );
    
              if (!point.visible) {
                value += point.y;
              }
    
              chart.setTitle({
                text: value
              });
            }
          }
        }
      }]
    

    Live demo: https://jsfiddle.net/BlackLabel/2Luk6pm3/

    API Reference: https://api.highcharts.com/class-reference/Highcharts.Chart#setTitle