5

I am learning React.js .In the tutorial the author use onClick with bind , but at some places he do not use the bind with the onClick. I can not get the difference between the two.

 <button onClick={this.handleAdd}>Add Item</button> 
1
  • 4
    Can you post the other example of using the bind method? Commented Feb 24, 2015 at 5:18

1 Answer 1

8

You might use bind in order to pass in a certain argument to the handler method.

For example:

render: function() { return _.map(list, function(item) { return <li onClick={this.clickItem.bind(this, item)}>{item.name}</li>; }); }, clickItem: function(item, event) { //do something with the clicked item } 

If you don't need to inject an argument, you don't need to bind since react always calls the handler method in the scope of the component - although this is changing soon

Sign up to request clarification or add additional context in comments.

2 Comments

That is not the reason you use the bind method: developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
Very true. But I think I posted this answer before React.Component existed (actually yeah, I reference the "coming change" in my answer). Back then, you always used React.createClass(), which meant that this.handleAdd would always be bound to the component instance, and you would never use bind unless you had an argument to pass. I guess you could override this if you wanted to, but that would've been really odd to do for a component's method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.