7

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}) })
George Salamanca
  • 180
  • 1
  • 3
  • 11

4 Answers4

8

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 });
  }
}
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
2

You should do a separate function that manages the event. And then bind the function to the constructor. For example

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};
    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }
render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }

Also, take in count this :

When using React you should generally not need to call addEventListener to add listeners to a DOM element after it is created. Instead, just provide a listener when the element is initially rendered.

Handling Events in react

0

use:

var self=this

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

Remove double quotes from this, it should be working.

Jatinder Kumar
  • 503
  • 6
  • 17
  • After i removed the double quotes it still says TypeError: self.setState is not a function HTMLButtonElement. i did var self=this; b.addEventListener("click", (self)=>{ self.setState({health:100}) }) – George Salamanca Apr 02 '18 at 05:12
  • I dont get an error message now but when I click the button, the value of this.state.health is still 0 – George Salamanca Apr 02 '18 at 05:22
0

No need const self= this;(optional) simply use arrow function.this work perfectly

b.addEventListener("click", () => {
    this.setState({ health: 100 });
  }
Rajbir
  • 31
  • 7