Open In App

What is the alternative of binding this in the constructor ?

Last Updated : 23 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The concept of binding this keyword is not reacted specifically but rather Javascript-specific. We need to bind this keyword because the value of this keyword in a simple function is undefined. For example, consider the code below. If this is a click handler in a functional component then the output will be undefined ( only in strict-mode, in non-strict-mode it will point to a global object ). 

Approach:

In all the methods below we have created a state of geek emoji in the App component. On clicking the button we will reduce the size of the geek emoji array by one.

There are 2 alternative ways to bind this keyword in React.

Steps to Create the React Application And Installing Module:

Step 1: Create a React application using the following command.

npx create-react-app app-8

Step 2: After creating your project folder i.e. folder name, move to it using the following command:

cd app-8

Step 3: After creating the ReactJS application, run the development server by the following command:

npm start

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

Method 1: Using onClick event handler

Binding this keyword in the onClick event handler with the help of bind(). Same as the previous method this approach to has performance implications because we keep on getting reallocated on every re-render. 

Syntax:

onClick={this.handleClick.bind(this)}

Example: Below is the implementation of the above method.

Javascript




import "./App.css";
import React, { Component } from "react";
 
export class App extends Component {
    constructor(props) {
        super(props);
        let styles = {
            width: "120px",
            color: "green",
            padding: "5px",
            margin: "2px",
            border: "2px solid green",
        };
        this.state = {
            mustKnowTopics: [
                <div style={styles}>
                    <h4> Searching </h4>
                </div>,
                <div style={styles}>
                    <h4> Sorting </h4>
                </div>,
                <div style={styles}>
                    <h4> BinarySearch </h4>
                </div>,
                <div style={styles}>
                    <h4> SlidingWindow </h4>
                </div>,
                <div style={styles}>
                    <h4> Stack's </h4>
                </div>,
                <div style={styles}>
                    <h4> Queue's </h4>
                </div>,
            ],
        };
    }
 
    handleClick = () => {
        let newTopics = [...this.state.mustKnowTopics];
        newTopics = newTopics.slice(0, newTopics.length - 1);
        this.setState({
            mustKnowTopics: [...newTopics],
        });
    };
 
    render() {
        return (
            <>
                <div
                    style={{
                        margin: "1rem",
                        display: "flex",
                        flexDirection: "column"
                    }}>
                    <>
                        {" "}
                        <h3> Must know topics</h3>
                        <div style={{ display: "flex", flexDirection: "row" }}>
                            {this.state.mustKnowTopics}
                        </div>
                    </>
                    <button
                        onClick={this.handleClick.bind(this)}
                        style={{ width: "100px", margin: ".5rem" }}>
                        Click to reduce the Must know Topic's array
                    </button>
                </div>
            </>
        );
    }
}
 
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

Method 2: Using an arrow function

Using an arrow function in the handleClick function. This is a much better approach towards binding this because it avoids the performance issues as in the previous two methods. Also, they use the value of this in the enclosing scope and no matter how much level of nesting we use it will refer to the correct context. This method uses lexical this binding which automatically binds them to the scope in which they are defined in.

Syntax:

handleClick = () => {
// code
}

Example: Below is the implementation of the above method.

Javascript




import "./App.css";
import React, { Component } from "react";
 
export class App extends Component {
    constructor(props) {
        super(props);
        let styles = {
            width: "120px",
            color: "green",
            padding: "5px",
            margin: "2px",
            border: "2px solid green",
        };
        this.state = {
            mustKnowTopics: [
                <div style={styles}>
                    <h4> Searching </h4>
                </div>,
                <div style={styles}>
                    <h4> Sorting </h4>
                </div>,
                <div style={styles}>
                    <h4> BinarySearch </h4>
                </div>,
                <div style={styles}>
                    <h4> SlidingWindow </h4>
                </div>,
                <div style={styles}>
                    <h4> Stack's </h4>
                </div>,
                <div style={styles}>
                    <h4> Queue's </h4>
                </div>,
            ],
        };
    }
 
    handleClick = () => {
        let newTopics = [...this.state.mustKnowTopics];
        newTopics = newTopics.slice(0, newTopics.length - 1);
        this.setState({
            mustKnowTopics: [...newTopics],
        });
    };
 
    render() {
        return (
            <>
                <div
                    style={{
                        margin: "1rem",
                        display: "flex",
                        flexDirection: "column"
                    }}
                >
                    <>
                        {" "}
                        <h3> Must know topics</h3>
                        <div style={{ display: "flex", flexDirection: "row" }}>
                            {this.state.mustKnowTopics}
                        </div>
                    </>
                    <button
                        onClick={this.handleClick}
                        style={{ width: "100px", margin: ".5rem" }}
                    >
                        Click to reduce the geek emojis
                    </button>
                </div>
            </>
        );
    }
}
 
export default App;


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads