Abin K Paul
Abin K Paul

Reputation: 181

Calling function in component class from Highcharts component in React

Trying to set a click listener on the Pie Chart made using HighCharts wrapper for react. I would like to manipulate state when a user clicks on a portion of the Pie Chart, but I can't seem to think of a way to set the listener to the click event. Setting click event to this.clickHandler wont work because this does not refer to the App Class. How can I set the function in the App component to be triggered on click

class App extends Component{

  state = {
    config:{
      chart: {
          plotBackgroundColor: null,
          plotBorderWidth: null,
          plotShadow: false,
          type: 'pie'
      },
      title: {
          text: 'Analysis'
      },
      tooltip: {
          pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
      },
      accessibility: {
          point: {
              valueSuffix: '%'
          }
      },
      plotOptions: {
          pie: {
              allowPointSelect: true,
              cursor: 'pointer',
              events: {
                  click: this.clickHandler
                  }
              },
              dataLabels: {
                  enabled: true,
                  format: '<b>{point.name}</b>: {point.percentage:.1f} % ({point.n}) '
              }
          }
      },
      series: [{
          name: 'Market Share in Percentage',
          size: 200,
          center: [150, 100],
          colorByPoint: true,
          data: [{
              name: 'Common Devices',
              y: 40,
              n: 243,
              sliced: true,
              selected: true
          }, {
              name: 'Unique First Devices',
              y: 50,
              n: 300,
          }, {
              name: 'Unique Second Devices',
              y: 10,
              n: 30
          }]
      }]
    },
   test:false
  }

  clickHandler = (event) => {
    console.log(event)
    if (event.point.name==="Common Devices"){
      this.setState({test:true})
    }
  }
  render(){
    return <div>
        <HighchartsReact options = {this.state.config}></HighchartsReact>
    </div>
  }
}

Upvotes: 2

Views: 360

Answers (1)

Alex
Alex

Reputation: 3991

As you mentioned,this does not refer to the App Class, so, change click: this.clickHandler to click: this.clickHandler.bind(this) and you should move state into the class constructor

 constructor(props) {
    super(props);

    this.state ={
    // Your state
   
  }

Sample can be found here.

Upvotes: 1

Related Questions