0

I have a bit of an understanding on how bind works, but in my component I'm using this alot and I'm a bit confused on what .bind(this) is doing and how it interacts with the onClick and onChange. I know that that this.addTodo is referring to the TodoInput class

class TodoInput extends Component {
constructor(props) {
super(props);

this.state = {
  value: 'test',
};

this.handleChange = this.handleChange.bind(this);
this.addTodo = this.addTodo.bind(this);
}

handleChange(e) {
console.log('CHANGE HERE');
}

addTodo(todo) {
 console.log('TODO:', todo);
}

render() {
 return (
   <div>
    <input type="text" value="" onChange={this.handleChange} />
    <button className="btn btn-primary" onClick={() => this.addTodo(this.state.value)}>Submit</button>
  </div>
);
  }
}
31piy
  • 23,323
  • 6
  • 47
  • 67
Joe Escobedo
  • 255
  • 1
  • 4
  • 15

1 Answers1

1

When you pass an instance method by reference, the context is lost. By explicitly binding it to the current instance, you can safely pass it by reference while maintaining the value of this

djfdev
  • 5,747
  • 3
  • 19
  • 38
  • And by instance, it is referring to the class component right? Since I am binding the function to the component, each time i used handleChange or addTodo it acts like ```new HandleChage``` or ``` new addTodo ``` – Joe Escobedo Mar 30 '18 at 03:51
  • Ive seen examples of bind on a much smaller scale on youtube videos, but nothing like this one. – Joe Escobedo Mar 30 '18 at 03:53