React event API and you

Yesterday we used the on-click event handler to manipulate state of our component and show off state full or the clarity rendering. Which is great, but I think we kind of jumped the gun with the on-click. Let's take a step back. Talk about just how react events work. React comes with a full event API where you define a prop, give it a callback. Those callbacks, then get called by react's synthetic event API. Whenever that event happens on your [inaudible 00:00:27].

This means that you never have to call add event listener again. You never have to worry about whether you've cleaned up your event callbacks or not. Let's look at how to properly configure event callbacks, so that you never have to worry about that this key worked ever again. Yesterday we built a button that when you click on it, becomes a larger button. We built that that using this on-click prompt which we added to the button, HTML element. That calls are this dot on-click call back. It's a function defined on our button class. It's defined as a fat arrow function which means that this is immediately bound to the class that we're defining it in.

When that's called, adding mouse over, we can define the mouse over event as a normal class function. Background becomes red. You can also define mouse out on click, button becomes big. Mouse into the button becomes red. Mouse out of the button it becomes white again. We're going to talk about actual styling later. On mouse over, this isn't going to work. I mouse over the button and we get huge error saying that this dot said state is not defined. Our function wasn't bound to our class. One option is we can say bind to this. It works, it turns red.

When we define mouse out by passing a fat arrow function directly in to on mouse out, that calls this mouse out. When we mouse over the button, it turns red. When we come back out, it turns white. When we click on it, it becomes a big button. These the three styles you can use for defining callbacks on events. You can define your handler as a fat arrow function directly, which means it's always bound to this class.

If you have your functions defined as normal class functions, then you have to make sure that you bind them to the object when you pass them into your event handler. You can then pass this down to children and so on. We're going to talk about that tomorrow, when we're going to talk about props going down and callbacks coming back up when you're building component architectures.

Know someone who wants to learn React and its whole ecosystem? Share 👇