1

This is not really a React specific question, but I think it helps to know the context. In a component I'm generating some table rows. Each row needs an onClick function that passes an id to the components handleUnlink method.

I got it to work with the code below, but it's making my head spin a bit and I have a feeling that this could be done in a simpeler way. Am I right?

var fn = function(id){
  return function(){
    this.handleUnlink(id);
  }.bind(this);
}.bind(this); 

var linkedListHtml = this.state.linkedList.map( p => {
  return(
    <tr key={p.id}>
    <td>{p.name}</td>
    <td><mui.Icon icon='action-highlight-remove' onClick={fn(p.id)}/></td>
    </tr>);
});

1 Answer 1

3

Function.prototype.bind() also does partial application of any additional arguments, so you should be able to do this instead:

onClick={this.handleUnlink.bind(this, p.id)}

Bonus: The this argument to bind() is redundant if you're using React.createClass() to create your component, as it auto-binds methods for you, so I usually end up writing a partial helper:

'use strict';
var slice = Array.prototype.slice
function partial(fn) {
  var partialArgs = slice.call(arguments, 1)
  return function() {
    return fn.apply(this, partialArgs.concat(slice.call(arguments)))
  }
}
module.exports = partial

...

var partial = require('./utils/partial')
// ...
onClick={partial(this.handleUnlink, p.id)}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, that's even better then I hoped for. \o/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.