-1

Why do I have to bind onClick method? In this case "this" refers to App class, render method or DOM element?

enter image description here

Lukas
  • 229
  • 3
  • 4
  • 10
  • Binding the context may be confusing, especially for newcommers. I would suggest you to use *arrow function* instead, which holds the proper context. – kind user Jul 10 '17 at 10:03

4 Answers4

0

Calling the function without bind way will set its context (this) to a global variable of an environment on which your JavaScript operates. In browsers, it is a window global variable.

bind is just core javascript. It's how binding events works. It's not a React concept.

Instead of binding a function inside the event handler, you can bind it in constructor itself.

constructor(props) {
       super(props);
       this.handleChange= this.handleChange.bind(this);
    }
Green Sand
  • 17
  • 4
0

You need to bind onClick because if you do not then this will refer to the global Object.

On the other hand if your onClick is defined inside any html tag like

Select is also considered as an element in reactjs and it provides its own this with which onClick event is binded.

So if you do not bind your event to local this of Select then it will throw an error

typeError:function not defined

So binding is mendatory.

Same applies if you are returning anything from with in a map like

this.state.something.map(function(holidays,i) {

return  
  <div>
    <Select onClick="this.function"/>
  </div>
}, this)
Alireza
  • 100,211
  • 27
  • 269
  • 172
Vikram Saini
  • 2,713
  • 1
  • 16
  • 33
0

Up ES6 you can change function "handleChange" like this :

handleChange = () => {
  this.setState ({checked: !this.state.checked});
}

Now you can call this function: onChange = {this.handleChange} . Hope will help you :)

Alireza
  • 100,211
  • 27
  • 269
  • 172
Voi Mập
  • 779
  • 3
  • 7
  • 22
-1

this is the App instance in this case.

As for what Function.prototype.bind does, the documentation describes it pretty well:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, [...]

If we didn't bind this (the App instance) to our handler function, then when handleChange is fired, the this inside of that function would be the <input> element that contains the onChange event handler.

By using bind, we force this to be the App instance inside of the handleChange event handler.

Mate Solymosi
  • 5,699
  • 23
  • 30