Binding event handlers to this is not just ReactJS-specific, it is a Javascript-specific concept because, in JS, the value of this in simple functions (non-arrow functions) is undefined by default (in strict mode), that is why there is a need to bind event handlers to this to access its properties within the handler function.
Usage of this inside a normal JS function (non-arrow function) as shown below results in an error:
TypeError:
function eventHandler(){
//a TypeError will be thrown
console.log(this);
}
Create a new React Application: Follow the below steps to create a project application:
Step 1: Create a new React application using the following command
npx create-react-app foldername
Step 2: After all the modules are installed and the root project directory i.e. foldername is created, move to it using the following command
cd foldername
Project Structure: The project structure will look like the following. We will write our code in the App.js file and then run the development server to view the output.
Let’s understand the error with an example:
Example: In this example, we’ll see the error and try to understand why it is happening:
App.js:
In the below code, we are not binding the click event handler to
this
Javascript
import React, { Component } from "react" ; import "./App.css" ; class App extends Component { constructor(props) { super (props); this .state = { text: "Sample Text" }; } //without binding the event handler to this clickHandler() { this .setState({ text: "Geeks For Geeks" }); } render() { return ( <div className= "App" > <button onClick={ this .clickHandler} style={{ padding: "5px" , marginTop: "15px" }} > Click Me </button> <h3 style={{ color: "green" }}> { this .state.text}</h3> </div> ); } } export default App; |
Step 3: Run the development server using the following command in the terminal to view the output
npm start
Output:
Explanation: In the above example, the state is being updated in the event handler on clicking the button but the setState method is not being executed because this is undefined within the function. It returns a TypeError and only when the event handler i.e. clickHandler will be bound to this, the setState method will work.
Below are the common ways to bind this to the event handler:
- The binding event handler in the constructor.
- The binding event handler in the render method.
Example 1: In this example, we will bind the clickHandler to this in the render method using the bind( ) method of JS
Javascript
import React, { Component } from "react" ; import "./App.css" ; class App extends Component { constructor(props) { super (props); this .state = { text: "Sample Text" }; } //the updated text will be displayed now on re-render clickHandler() { this .setState({ text: "Geeks For Geeks" }); } //binding clickHandler to 'this' in the render method render() { return ( <div className= "App" > <button onClick={ this .clickHandler.bind( this )} style={{ padding: "5px" , marginTop: "15px" }} > Click Me </button> <h3 style={{ color: "green" }}> { this .state.text}</h3> </div> ); } } export default App; |
Output:
Example 2: In this example, we will bind the clickHandler to this in the constructor method of the class
Javascript
import React, { Component } from "react" ; import "./App.css" ; class App extends Component { constructor(props) { super (props); //initial state this .state = { text: "Hover over me" , color: "yellow" , fontColor: "black" }; //binding event callback to this in the constructor this .hover = this .hover.bind( this ); } //updating the state onMouseEnter hover() { this .setState({ text: "Geeks For Geeks" , color: "green" , fontColor: "white" }); } //binding clickHandler to 'this' in the render method render() { return ( <div className= "App" style={{ backgroundColor: this .state.color, color: this .state.fontColor, borderRadius: "120px" , width: "200px" , height: "100px" , textAlign: "center" , paddingTop: "20px" , fontWeight: "bold" }} onMouseEnter={ this .hover} > { this .state.text} </div> ); } } export default App; |
Output: