Open In App

What’s an alternative way to avoid having to bind to this in event callback methods ?

In React class-based components, accessing `this` within a method or event callback necessitates explicit binding to enable state manipulation with `setState`. Without binding, accessing `this` in such contexts leads to a TypeError due to its default undefined value within class methods.

Usually, binding this with the event callback is done by:



Approach: In modern JS i.e. ES6, there’s an alternative way to avoid having to bind this to event callbacks and that is using arrow functions. Due to certain properties of arrow functions, this can be accessed within the class methods or event callbacks without using bind(). This is because:

Steps to Create the React Application

Step 1: Create a new react application ‘binding’ using the following command



npx create-react-app binding

Step 2: Move into the root project directory using the following command

cd binding 

Project Structure:

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",
}

Example 1: In this example, we will call the event callback method using an arrow function.




import React, { Component } from "react";
import "./App.css";
 
class App extends Component {
    constructor(props) {
        super(props);
        //initial state
        this.state = { text: "Click Me!", color: "lightblue" };
    }
 
    //updating the state
    clickHandler() {
        this.setState({ text: "Geeks For Geeks", color: "lightpink" });
    }
 
    //calling the clickHandler using an arrow function
    render() {
        return (
        <>
        <h3>Alternative this binding</h3>
            <div className="App"
                onClick={() => this.clickHandler()}
                style={{
                    backgroundColor: this.state.color,
                    textAlign: "center",
                    padding: '10px',
                    width: '200px',
                    height: '200px'
                }}>
                {this.state.text}
            </div>
            </>
        );
    }
}
 
export default App;

Step to run the application: Run the application using the following command in the terminal to view the output:

npm start

Output:

updating the state on click

Example 2: In this example, we will assign the event callback to a class property as an arrow function.




import React, { Component } from "react";
import "./App.css";
 
class App extends Component {
    constructor(props) {
        super(props);
        // Initial state
        this.state = { text: "Enter input in the box!" };
 
        // Updating state within event
        // handler (as an arrow function)
        this.handleChange = (event) => {
            this.setState({ text: event.target.value });
        }
    }
 
    render() {
        return (
            <>
                <h3>onChange Event</h3>
                <input onChange={this.handleChange} />
                <p style={{
                        padding: "5px",
                        color: "green" }}>
                    {this.state.text}</p>
            </>
        );
    }
}
 
export default App;

Step to run the application: Run the application using the following command in the terminal to view the output:

npm start

Output:

updating the state on change in input


Article Tags :