Thursday, January 16, 2025
Google search engine
HomeLanguagesWhat is the alternative of binding this in the constructor ?

What is the alternative of binding this in the constructor ?

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 ). 

Syntax:

function handleClick(event){
   console.log(this); // 'this' is undefined
}

Let’s understand with examples.

Creating React Application And Installing Module:

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

npx create-react-app foldername

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

cd foldername

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

npm start

Project structure: It will look like the following.

There are 3 alternative ways to bind this keyword in react.

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.

First Method:  We can use an arrow function in the render method where we are attaching the event handler. There is one performance implication in this method i.e. whenever the component re-renders the function will be created again and again. This might create performance issues if the web app or the component does a lot of re-rendering.

Syntax:

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

App.js




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 Must know Topic's array
          </button>
        </div>
      </>
    );
  }
}
  
export default App;


Step to run the application: Open the terminal and type the following command.

npm start

Output:

Second Method: 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)}

App.js




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;


Output:

Third Method: 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
}

App.js




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;


Output:

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