ReactJS | Binding Event Handlers
Last Updated :
11 Nov, 2022
In ReactJS, we need to bind events so that the this keyword would not return an "undefined". In this article, we are going to see the different ways in which we can bind event handlers in ReactJS.
First, let's make a new class component and name it Binding.js. Make a simple class component with a simple message state and render a simple button as shown below. Don't forget to import this component in App.js file.
Binding.js:
JavaScript
import React, { Component } from 'react';
class EventBind extends Component {
constructor(props) {
super(props)
this.state = {
message: 'Welcome'
}
}
render() {
return (
<div>
<h3>{this.state.message}</h3>
<button>Click</button>
</div>
)
}
}
export default EventBind;
Let's write an event that changes the state of message from 'Welcome' to 'Farewell' whenever the button is clicked. So let's define an onClick method to the button and write an event handler clickHandler().
JavaScript
import React, { Component } from 'react';
class EventBind extends Component {
constructor(props) {
super(props)
this.state = {
message: 'Welcome'
}
}
clickHandler() {
this.setState({
message:'Farewell'
})
}
render() {
return (
<div>
<h3>{this.state.message}</h3>
<button onClick={this.clickHandler}>Click</button>
</div>
)
}
}
export default EventBind;
Output: Now if we run the application and click on the button, we get an error. This is because this returns an "undefined". This is why we need to bind our events.
Error- Binding Event Handler in Render Method: We can bind the handler when it is called in the render method using bind() method.
JavaScript
import React, { Component } from 'react';
class EventBind extends Component {
constructor(props) {
super(props)
this.state = {
message: 'Welcome'
}
}
clickHandler() {
this.setState({
message:'Farewell'
})
}
render() {
return (
<div>
<h3>{this.state.message}</h3>
<button onClick={this.clickHandler.bind(this)}>
Click</button>
</div>
)
}
}
export default EventBind;
- Binding Event Handler using Arrow Function: This is pretty much the same approach as above, however, in this approach we are binding the event handler implicitly. This approach is the best if you want to pass parameters to your event.
JavaScript
import React, { Component } from 'react';
class EventBind extends Component {
constructor(props) {
super(props)
this.state = {
message: 'Welcome'
}
}
clickHandler() {
this.setState({
message:'Farewell'
})
}
render() {
return (
<div>
<h3>{this.state.message}</h3>
<button onClick={() => this.clickHandler()}>
Click
</button>
</div>
)
}
}
export default EventBind;
- Binding Event Handler in the Constructor: In this approach, we are going to bind the event handler inside the constructor. This is also the approach that is mentioned in ReactJS documentation. This has performance benefits as the events aren't binding every time the method is called, as opposed to the previous two approaches. Just add the following line in the constructor for this approach,
JavaScript
this.clickHandler = this.clickHandler.bind(this)
- Binding Event Handler using Arrow Function as a Class Property: This is probably the best way to bind the events and still pass in parameters to the event handlers easily.
JavaScript
import React, { Component } from 'react';
class EventBind extends Component {
constructor(props) {
super(props)
this.state = {
message: 'Welcome'
}
}
clickHandler = () => {
this.setState({
message:'Farewell'
})
}
render() {
return (
<div>
<h3>{this.state.message}</h3>
<button onClick={this.clickHandler}>
Click
</button>
</div>
)
}
}
export default EventBind;
Output: All of these approaches offer the same solution to the problem, you can use any of them according to your requirements.
State after button is clicked
React Event Handling in React
Similar Reads
How to bind event handlers in React? Binding event handlers in React is a fundamental concept that ensures interactive and responsive web applications. React, a popular JavaScript library for building user interfaces uses a declarative approach to handle events. This article explores various methods to bind event handlers in React, hig
3 min read
ReactJS Data Binding Data binding is a technique that binds data sources from the provider and consumer together and synchronizes them. In other words, Data Binding means sharing data between components to view and view to component.Data binding in React can be achieved by using a controlled input. A controlled input is
7 min read
ReactJS bind() Method The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component. Syntax:this.function.bind(this,[arg1...]);Parameter:It accepts two parameters, the first parameter is thethis: keyword used for binding [arg1...]: the sequence of argumen
2 min read
Why we need to bind event handlers to this ? In JavaScript, when using regular functions, `this` can be undefined by default. To fix this, you bind functions to a specific value for `this` to avoid errors. This applies not only in ReactJS but across JavaScript for accessing properties inside functions. Usage of this inside a normal JS function
3 min read
How are events handled in React? Modern webpages rely on user interactions, triggering events like clicks or keypresses. React facilitates event handling with built-in methods, allowing developers to create listeners for dynamic interfaces and responses. JavaScript events, inherent to the DOM, use bubbling propagation by default, m
2 min read
React onKeyPress Event React onKeyPress event is an event listener that is used to detect the key press in a browser. onKeyPress is now deprecated because it does not work for all keys (like CTRL, SHIFT, and ALT) in all browsers, so onKeyDown is a new event listener that is used to detect the key press event. It is simila
2 min read