Thursday, November 28, 2024
Google search engine
HomeLanguagesWhat’s an alternative way to avoid having to bind to this in...

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

While working with class-based components in ReactJS, accessing this inside a class method or an event callback requires binding the method with this explicitly. This is required to access or update the state using the setState method from within the event callback. A TypeError is thrown if this is accessed inside the event callback without binding it. This is because, by default, inside a class method, this is undefined. 

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

  • binding it in the class constructor.
  • binding it in the render method.

Alternative 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:

  • Arrow functions use lexical scoping i.e. it binds this automatically to the scope in which the function is defined
  • In JS, functions are also considered data so they can be assigned to a class property. Thus, the event callback method can be assigned as an arrow function to a class property.

Let’s understand this approach using suitable examples:

Creating a React Application: Follow the below steps to create a 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: The project should look like below:

project structure

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

Javascript




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.

Javascript




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;


Output:

updating the state on change in input

Explanation: In the above example, the event object is passed to the event callback using which the state is updated whenever the input value changes. This is the best alternative method to avoid having to bind this to an event callback since it doesn’t cause any performance issues unlike the previous example in which on each re-render, a new function is created, which can hinder the performance of the application on multiple re-renders.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments