ReactJS | Binding Event Handlers

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 to forget to import this component in App.js file.

Binding.js:

Javascript



filter_none

edit
close

play_arrow

link
brightness_4
code

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;

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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;

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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;

chevron_right


  • 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

filter_none

edit
close

play_arrow

link
brightness_4
code

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;

chevron_right


  • 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

filter_none

edit
close

play_arrow

link
brightness_4
code

this.clickHandler = this.clickHandler.bind(this)

chevron_right


  • 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

filter_none

edit
close

play_arrow

link
brightness_4
code

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;

chevron_right


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-js-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.