Mosh React tutorial (part 2)

final source

ref – https://www.youtube.com/watch?v=Ke90Tje7VS0&t=0s&list=LLJEwHxS-Vsf-N8xSFHeMirw&index=4
Starts at 1:01:06 of the video

Handling Events

All those standard DOM events are available via the JSX.

We’ll use onClick and have it respond to our function handleIncrement.
However, when we execute the function, we notice that the this object is undefined.

Its because we need to bind the event handler.

But why is it that in an event handler function, the this object is undefined?

Depending on how a function is called, the ‘this’ changes.

The this reference will always return the calling object.

However, if the function is called as standalone, it will return window object.
If the standalone function is called within ‘strict mode’, it will return undefined.

And that is the reason, our event handler function does not have access to ‘this’.

Notice that handleIncrement is a REFERENCE. We didn’t execute the function yet. If the function was executed right away, then it will correctly call the function, and the function will be able to display this.

But for event handlers, since we pass the handleIncrement function reference, when it is used, it will be used in another function of a different environment. It will not be able have class Counter as its surrounding environment. It will be used in its own environment, namely, as a standalone function. Hence standalone functions (in a ‘strict mode’) will have undefined as the this object.

use ‘bind’ in the constructor

We implement a constructor function. Make sure you call super to initiate its parent class.
Then we bind the current this object to that function. So that when the reference of that function gets passed around, the this will always return to this object, and subsequently, the properties in this classCounter.

Use custom constructor to bind your event handlers to class Counter

Now, this.state.count will be valid.

The reasoning for using bind is explained here

Sometimes we need to pass in objects to our event handlers. In order to do this without having to execute the event handler via syntax, we define an anonymous function. That way, the event handler only executes when you click:

Pass in objects to handle event handlers like so:

or when you’re trying to loop through something and pass in an object to event handlers:

Updating the State

In react, we DO NOT modify the state directly. Instead we use setState, which is a method inherited from the base class Component.

We’re telling React we’re updating the state. It will then diff it with the previous virtual DOM. Finally, it applies the changes to the real DOM.

full code

What happens when State Changes

React state changes, Virtual DOM, reconciliation