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
Project Structure: The project should look like below:
Example 1: In this example, we will call the event callback method using an arrow function.
Step to run the application: Run the application using the following command in the terminal to view the output:
Example 2: In this example, we will assign the event callback to a class property as an arrow function.
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.
Please Login to comment...