Skip to content

Instantly share code, notes, and snippets.

@parwatcodes
Last active August 23, 2017 06:01
Show Gist options
  • Save parwatcodes/fb435fb3ce5b81dd21d438deea890d61 to your computer and use it in GitHub Desktop.
Save parwatcodes/fb435fb3ce5b81dd21d438deea890d61 to your computer and use it in GitHub Desktop.
Why we have to bind this in react, if not bind we have to use arrow function
class HelloWorld extends React.Component {
constructor(props) {
super(props);
this.state = { message: 'Hi' };
}
logMessage() {
console.log(this.state.message);
}
render() {
return (
// here what does this represent
<input type="button" value="Log" onClick={this.logMessage} />
);
}
}
@parwatcodes
Copy link
Author

parwatcodes commented Aug 22, 2017

to call logMessage in onclick event either i have to bind it, or use arrow notation to define logMessage function, but how does the process work

@benawad
Copy link

benawad commented Aug 22, 2017

class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: 'Hi' };
  }

  logMessage = () => {
    console.log(this.state.message);
  }

  render() {
    return (
       // here what does this represent
      <input type="button" value="Log" onClick={this.logMessage} />
    );
  }
}

@parwatcodes
Copy link
Author

parwatcodes commented Aug 22, 2017

class HelloWorld extends React.Component {
  constructor(props) {
    super(props);
    this.state = { message: 'Hi' };
  }

  logMessage() {
    // here this represents the <input tag context
    console.log(this.state.message);
  }

  render() {
    return (
       // logMessage is passing this context of input to logMessage method
      <input type="button" value="Log" onClick={this.logMessage} />
    );
  }
}

everytime an onclick event is occurred logMessage is bound to the input context

so to bound the instance of component either we have to use bind or arrow notation

after the code is complied

<input type="button" value="Log" onClick={this.logMessage} />
the upper line will be compiled and converted to
React.createElement('input', { onChange: this.logMessage, value: "Log" }) // here this represents component context

remember this always represents to the closet object,

let A = { onChange: this.logMessage, value: "Log" }

A is an object,
and is same as

{ onChange: this.logMessage() { console.log(this.state) } , value: "Log" }

// consoles undefined, cause this here represents object and there is no state property

so the this used inside the logMessage will be the context of { onChange: this.logMessage, value: "Log" } object. So, to solve this issue we have to use bind to take the component context in this, or use => notation in function

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