HANDLING EVENTS

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.
<button onClick={clickMe}>Click Me</button>

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 :

class Changecolor extends React.Component {
clickMe() {
alert("You have clicked this button");
}
render() {
return (
<button onClick={this.clickMe}>click me to change color</button>
);
}
}

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.

class Changecolor extends React.Component {
clickMe = () => {
alert(this);
/*
The 'this' keyword refers to the component object
*/
}
render() {
return (
<button onClick={this.clickMe}>Change a Color</button>
);
}
}

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:

class ChangeColor extends React.Component {
constructor(props) {
super(props)
this.clickMe = this.clickMe.bind(this)
}
clickMe() {
alert(this);
/*
Thanks to the binding in the constructor function,
the 'this' keyword now refers to the component object
*/
}
render() {
return (
<button onClick={this.clickMe}>click me!</button>
);
}
}