0

I am learning ReactJS and I have seen many available answers but I am unable to understand that why this.setStateHandler = this.setStateHandler.bind(this); is being used in the code given below? Why we cannot simply call the setStateHandler function on button click without this code of line written in the constructor (as we normally do in other programming languages)? Please explain in simple terminology.

Code

import React from 'react';

class App extends React.Component {
   constructor() {
      super();

      this.state = {
         data: []
      }

      this.setStateHandler = this.setStateHandler.bind(this);
   };

   setStateHandler() {
      var item = "setState..."
      var myArray = this.state.data;
      myArray.push(item)
      this.setState({data: myArray})
   };

   render() {
      return (
         <div>
            <button onClick = {this.setStateHandler}>SET STATE</button>
            <h4>State Array: {this.state.data}</h4>
         </div>
      );
   }
}

export default App;
Agha
  • 401
  • 2
  • 6
  • 13

1 Answers1

1

context aka this needs to be set to point to your instance if you need to use any methods or properties

by default, a normal DOM event handler function would use this as the element that triggers the event. in react+strict mode, this can be undefined, hence exception 'setState' of undefined is not a function, unless you bind it to the instance or call it in an arrow function (keeping context)

so either do what you do or:

// arrow keeps context
onClick={e => this.handleClick(e)}
// experimental / proposal
onClick={::this.handleClick}

// needs class properties transform, binds to instance via arrow
handleClick = event => {
  // stuff on this, then just onClick={this.handleClick}
}

this has to be the most common question on this tag...

keep in mind that many of the methods involve creating a new function on the fly in each render(){}, which comes at a performance cost - so your method is preferred or the class properties transform (which does the same)

see How can I tell when this.setState exists in ES6? etc

Dimitar Christoff
  • 26,147
  • 8
  • 50
  • 69