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 (non-arrow function) as shown below results in an error:
TypeError:
function eventHandler(){
//a TypeError will be thrown
console.log(this);
}
Steps to Create React Application:
Step 1: Create a new React application using the following command
npx create-react-app foldername
Step 2: Moving to the project directory using the following command
cd foldername
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Explanation: In the below 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.
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’ll see the error and try to understand why it is happening:
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: "Beginner For Beginner" }); } 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:
Example 2: 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: "Beginner For Beginner" }); } //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 3: 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: "Beginner For Beginner" , 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:
Contact Us