Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access props and state of current component in React JS within an event handler

I am using Highcharts.js in conjunction with React.js. I want to re-render the view when a user clicks a point in Highcharts. To do this, I need to access the props variable in the click handler. Normally, I would just use this.props to update the props, but this won't work in an event handler. Therefore, how do I access the current component as a variable in the event handler so I can access its props? Is there a better way of doing what I am trying to do?

My config variable for HighCharts looks something like this. To clarify, this code is coming from the render function of the same component.

var config = {
      ...
      plotOptions: {
          series: {
              cursor: 'pointer',
              point: {
                  events: {
                      click: function (event) {
                        //the `this` variable does not have props or state here
                        //`this` refers to the point object on the graph here
                      }
                  }
              }
          }
      },
    };

Thanks for your help.

like image 261
sameetandpotatoes Avatar asked Oct 20 '22 07:10

sameetandpotatoes


1 Answers

You could define the click handler function somewhere outside the config variable, and it should have access to everything outside the scope of the event.

myRerenderFunction(e) { /* do something */ } // define function here...

var config = {
      ...
          events: {
              click: myRerenderFunction // ...and it's accessible since they're defined in the same scope
          }
    };

Or you could just put the rerendering itself outside the click handler.

myRerenderFunction(e) { /* do something */ } // This is now a closure...

var config = {
      ...
          events: {
              click: function(e) {
                  /* Do something with the event */
                  myRerenderFunction(e); // ...which means you can access it from inside the click handler function
              }
          }
    };

Or you could just store the current this as a closure.

var whateverScopeThisIs = this;

var config = {
      ...
          events: {
              click: function(e) {
                  /* Do something with the event */
                  whateverScopeThisIs.doSomething(e);
              }
          }
    };

You've got plenty of options, something along those lines should work.

like image 80
Jan Avatar answered Oct 21 '22 23:10

Jan