React passing parameter via onclick event using ES6 syntax

Remember that in onClick={ ... }, the ... is a JavaScript expression. So

... onClick={this.handleRemove(id)}

is the same as

var val = this.handleRemove(id);
... onClick={val}

In other words, you call this.handleRemove(id) immediately, and pass that value to onClick, which isn’t what you want.

Instead, you want to create a new function with one of the arguments already prefilled; essentially, you want the following:

var newFn = function() {
  var args =;

  // args[0] contains the event object
  this.handleRemove.apply(this, [id].concat(args));
... onClick={newFn}

There is a way to express this in ES5 JavaScript: Function.prototype.bind.

... onClick={this.handleRemove.bind(this, id)}

If you use React.createClass, React automatically binds this for you on instance methods, and it may complain unless you change it to this.handleRemove.bind(null, id).

You can also simply define the function inline; this is made shorter with arrow functions if your environment or transpiler supports them:

... onClick={() => this.handleRemove(id)}

If you need access to the event, you can just pass it along:

... onClick={(evt) => this.handleRemove(id, evt)}

Leave a Comment