Handling Events
Handling events with React elements is very similar to handling events on DOM elements. There are some syntax differences :
- React events are named using camelCase, rather than lowercase.
- With JSX you pass a function as the event handler, rather than a string.
Event Handlers
A good practice is to put the event handler as a method in the component class:
Example :
Put clickMe function inside the Changecolor component :
Bind this
For methods in React, the this keyword should represent the component that owns the method.
That is why you should use arrow functions. With arrow functions, this will always represent the object that defined the arrow function.
why Arrow Functions?
In class components, the this keyword is not defined by default, so with regular functions the this keyword represents the object that called the method, which can be the global window object, an HTML button, or whatever.
If you *must* use regular functions instead of arrow functions you have to bind this to the component, instance using the bind() method :
Example :
Make this available in the clickMe function by binding it in the constructor function: