0

I'm not quite sure what does .bind(this) is exactly doing in this example? Does it simply connect the specified function to the other components of the code such as this.state?

constructor(props) {
   super(props);
   this.state = {
      input: '',
      messages: []
   }
   this.handleChange = this.handleChange.bind(this);
   this.submitMessage = this.submitMessage.bind(this);
}
Konstantink1
  • 575
  • 1
  • 8
  • 26
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind – Andreas Mar 20 '20 at 12:32
  • 1
    .bind is setting the context for 'this' as an alternative you can use handleChange=()=>{} arrow function which will automatically resolve to use this – muddassir Mar 20 '20 at 12:34
  • 1
    have a look https://medium.com/shoutem/react-to-bind-or-not-to-bind-7bf58327e22a – Sanat Gupta Mar 20 '20 at 12:34
  • 1
    Just a side note: You don't need to bind anymore. Instead, you can use class properties with arrow funtcions. like: hanldeChange = (e)=>{} – i.brod Mar 20 '20 at 12:36

1 Answers1

3

"bind" method is used to pass the context (e.g. "this") to javascript function when it will trigger.

In this case "this" of react component passed to "handleChange" method in the constructor,
so when "handleChange" will invoke, if there is use of "this" inside it code, "this" will get the value of parent component.

handleCahnge() {
  this.sendSomethingToServer(); // this is react component
}

Otherwise, (without using "bind") If some event triggers the function the context will be context of event (this will be the event target element instead of conponent)

You can avoid use "bind" syntax is you use arrow function syntax:

handleCange = () => { this.sendSomethingToServer() };

happyZZR1400
  • 2,387
  • 3
  • 25
  • 43