React Event Listeners
Handling Events
Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences:
- React events are named using camelCase, rather than lowercase.
- With JSX you pass a function as the event handler, rather than a string.
//HTML
<button onclick="greet()">
Say Hello!
</button>
//JSX
<button onClick={greet}>
Say Hello!
</button>
Now when you write a function in React it is very important that you bind it. Let's look at an example.
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
//It is important to bind the function. If you do not then the function will not work and you will receive an error when you try and run it.
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault();
console.log('The button was clicked.');
}
render() {
return (
<form onClick={this.handleClick}>
<button>Click Me!</button>
</form>
);
}
}
The reason we have to bind it is so that the this
will be part of the constructor and not just part of the new function you created.
An alternative, but experimental, way of writing functions without having to bind them is like this:
//This syntax ensures `this` is bound within handleClick, without having to explicitly bind it up in the constructor
handleClick = () => {
console.log('this is:', this);
}
To learn more about the this
keyword, you can refer to our write up on it here
But let's pay attention to the syntax when we add our event listener.
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
With event listeners in React we:
- Put the listener (
onClick
in this example) inside of the opening tag of the element we will be using it on. - Camelcase the event listener. i.e.
onClick
,onSubmit
,onChange
etc... - For Class Based Components
- Call the function with the keyword
this
. ex:<button onClick={this.handleClick}>
- For Function Based Components
- Call the function with just the function name. ex:
<button onClick={handleClick}>
Passing arguments
If you want to pass an argument into an event handler then you would do it in on of the following ways:
<button onClick={(e) => this.handleClick(id, e)}>Click Me</button>
or
<button onClick={this.handleClick.bind(this, id)}>Click Me</button>