If you want to add onclick event listeners to any HTML element, you can just do this:
In React, it’s very similar. Just like this:
Two clearly visible differences in the syntax:
- The events name is in camelCase and not in lowercase.
- Function is passed as the event handler and not a string.
Preventing default behavior in React
In React, we can not return false to prevent the default behavior. We must use preventDefault.
HTML prevent default
Click me
React prevent default
In React, we need to add the function separately.
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log('The link was clicked.');
}
return (
Click me
);
}
addEventListener in React
Actually, in React, we don’t need to call addEventListener after the DOM element is created. Instead, we provide the listener when the element is rendered initially.
this in React JSX
In a JavaScript class, by default methods are not bound. We need to bind them. So, in React, if you want to call a method without (), you need to bind the method.
For e.g.
//in this case, we need to bind the method and then pass it
onClick={this.handleClick}
Like this:
...
...
constructor(props) {
...
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
...
...
Here’s the working example:
Passing Arguments to Event Handlers
If we use an arrow function, we have to explicitly specify the event. Like this:
But, if we use bind then we the event is automatically forwarded.
Source: React Docs
addEventListener arguments DOM event examples