2

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>
  }
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.