Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

The bind function

If you observe a bit more closely inside the button’s event listener you will see something very strange, a ‘bind’ method attached to the function you have created in the class.

What is this? Is this necessary?

The answer is yes! Normally every function you create inside a component (inside a class), you want to change some properties, variables that are also part of this component. In order to achieve this result you must use the keyword ‘this’ , in order to gain access to these variables.

The problem is, that anytime you use the keyword ‘this’ inside the function, you create a reference NOT to the class, but to the element that triggers the event and eventually the function (that means the button element!!). So if you want to change a variable that has been created inside the class (let’s say with the property’s name, name) you have to go to the function and say

this.name = ‘Jake’;

But the this keyword means to whoever calls the event, so the compiler understands:

button.name = ‘Jake’;

DOM elements don’t have such properties, so this will throw an error.

What we can do, is to change the point of reference of the this keyword, so when used inside the function, instead of pointing to the button, to point to the class. And that’s exactly what the bind does. It changes the point of reference of the function to the current context (which is the class component).

At the beginning maybe it seems a weird syntax but at the end you will get used to it. It's like a react poem you have to learn by heart.