pawan kumar
pawan kumar

Reputation: 131

How to call react function on click event of react apex chart

I want to call react function on click event of react apex chart. While cliking on apex chart bar or pie chart slice , i want to call react function example:-

dataPointSelection: function (event, chartContext, config) {
this.myFunction();
}

I can't call myFunction() from here

Upvotes: 0

Views: 1954

Answers (4)

Samanja Cartagena
Samanja Cartagena

Reputation: 150

data point index will not work if the value is 0. For example, if you have an apex bar chart but the value of the bar chart is 0.Then datapoint index will be -1. You may still want to click on the x axis label. In that case, this will work.

chartOptions: {
     chart: {
         id:'barChart',
         type: 'bar',
         height: 250, 
     events: {
      click: function (event, chartContext, config) {
       if(config.dataPointIndex <0){
       var chartName = event.target.firstChild.data
       console.log(labelName)
      }
      else{
     var chartName = config.dataPointIndex
         }
       }
      }
    }
   }

Otherwise, go with config.datapointindex to click on the bar chart but to click on the labels the best is to use event.target.firstChild.data I have written an article config.dataPointIndex and how to click on bar charts but with Vue JS. Same logic though https://samchowdhury.medium.com/how-do-you-make-a-bar-chart-clickable-in-apex-chart-with-vue-js-3ab3e0730e94 Hope this helps!

Upvotes: 0

pawan kumar
pawan kumar

Reputation: 131

simply do this:- chart: { id: "basic-bar",

                events: {
                    click: (event, chartContext, config) => {
                        this.myFunction(config.dataPointIndex)
                       
                    }
                },
            },

things to notice is " => "

Upvotes: 0

Francesco Orsi
Francesco Orsi

Reputation: 2089

if you need by the click, this is better

chart: {
    type: 'area',
    events: {
        click(event, chartContext, config) {

            console.log(config.config.series[config.seriesIndex])
            console.log(config.config.series[config.seriesIndex].name)
            console.log(config.config.series[config.seriesIndex].data[config.dataPointIndex])
            
            yourFunctionHere();
            
        }
    }
}

documentation events https://apexcharts.com/docs/options/chart/events/

Upvotes: 0

pawan kumar
pawan kumar

Reputation: 131

There is simple way to do this:-

 dataPointSelection: (event, chartContext, config) => {
this.myFunction();
}

I was missing => to call function Actually you have to call react methods from an arrow function, as this is currently pointing to the chart instance and not the react instance.

Upvotes: 1

Related Questions