Search code examples
reactjscanvasjs

CanvasJS React - How to make a pie chart slice highlight (aka explode) while at the same time handling the click event


I'm working in React and using this pie chart from canvasjs: https://canvasjs.com/docs/charts/chart-types/html5-pie-chart/

The chart has an optional 'click' function for handling events. Here is the documentation for that. https://canvasjs.com/docs/charts/chart-options/data/click/

The problem is when I implement 'click', and call a function to update my label (in a parent component) it changes the default behavior and no longer expands the slice.

I've tried lots of different things to fix it, but it seems I cannot get around the problem.

This code works to update the label in the parent - notice the line 'click: this.props.onSliceSelected'. I can then get the slice label from the event and update my label.

But as mentioned, the slice no longer expands when I do this.

data: [{
                type: "pie",
                animationEnabled: true,
                startAngle: 75,
                toolTipContent: "Select: <b>{label}</b> - {y}% of Total",
                showInLegend: false,
                legendText: "{label}",
                indexLabelFontSize: 16,
                indexLabelFontColor: "white",
                indexLabel: "{label}",
                click: this.props.onSliceSelected,
                dataPoints: sortedData,
                

            }]

I have tried to many other things to ensure the slice is getting selected - most involved trying to set exploded = true on the datapoint.

I cannot find a working example of how to do this anywhere.

Appreciate any ideas.

EDIT - Here is a screen shot, I need to update 'selected task' (outside of the chart and in the parent component). Right now the label will update, but the chart will not expand!

enter image description here


Solution

  • To update label in pie chart on clicking each slice, you can update dataPoints[index].label in chart-options and call chart.render(). Here is a working StackBlitz for the same.