Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot call this.setState in addEventListener function

Tags:

reactjs

enter image description here

I am trying to change the state on the click of a button I created through DOM methods. I tried passing "this" as a variable through the arguments of the function

var self="this"
b.addEventListener("click", function(self){
    self.setState({health:100}) })

and also tried adding .bind(this) at the end of the function but no luck.

b.addEventListener("click", function(){
    this.setState({health:100}) })
like image 439
George Salamanca Avatar asked Apr 02 '18 04:04

George Salamanca


1 Answers

This issue can be handled using right declaration and definition of self. OR with the help of arrow function(implicit Lexical scope)

componentDidMount(){

  //assuing b defined

  //1.  if you want to use self
  const self = this; //  this should not be double quoted;
  b.addEventListener("click", function () {
    self.setState({ health: 100 });
  }

  // 2. using arrow function ( implicit lexical scope) 
  b.addEventListener("click", ()=> {
    this.setState({ health: 100 });
  }
}
like image 115
RIYAJ KHAN Avatar answered Nov 14 '22 03:11

RIYAJ KHAN