Skip to content

Instantly share code, notes, and snippets.

@Ghanshyam-K-Dobariya
Last active August 20, 2019 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ghanshyam-K-Dobariya/eaf037650dc47b22c038a03cbe16d0cd to your computer and use it in GitHub Desktop.
Save Ghanshyam-K-Dobariya/eaf037650dc47b22c038a03cbe16d0cd to your computer and use it in GitHub Desktop.
Value of this inside react component method

In a JavaScript method, the value of this has nothing to do with the class on which it was defined. Instead, it depends on the object that it was called upon.

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  render() {
    var { handleClick } = this;
    const style = this.state;
    return (
      <div>
        <button onClick={() => this.handleClick()} style={style}>
          Click Me - 1
        </button>
        <p />
        <button onClick={() => handleClick()} style={style}>
          Click Me - 2
        </button>
        <p />
        <button onClick={this.handleClick} style={style}>
          Click Me - 3
        </button>
        <p />
        <button onClick={this.handleClick.bind(this)} style={style}>
          Click Me - 4
        </button>
      </div>
    );
  }

  handleClick() {
    this.setState({ backgroundColor: "#f6f6f6" });
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

@ time of mentioning function to onClick property you have to give just a definition of funtion, you are not supposed to call that function 😂.

Like below is invalid - will result in infinite function calling

 <button onClick={this.handleClick()} style={style}>
   Click Me - I will result in infinite calling of handleClick
 </button>

Now coming back to value of this inside function.

  1. Button 1 will work because of arrow function.
  2. Button 2 will not work because method is invoked without this
  3. Button 3 will not work because you are just giving a method's definition
  4. Button 4 will work because you are giving a definition of function with binded this

References

1. When should I use arrow function in React

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment