I have a react component where I am iterating over a list and creating rows. In each row, there is a delete button. When the delete button is clicked, I want to pass a reference to the element in that row.
var TagTable = React.createClass({ onTagDelete: function(tagName) { this.props.onTagDelete(tagName); }, render: function () { return R.table({className: "bg-box padded"}, [ R.thead({}, R.tr({}, [ R.th({}, ""), R.th({}, "Tag"), R.th({}, "Regexes") ])), R.tbody({}, this.props.tags.map(function (tag) { return R.tr({}, [ R.td({}, R.button({onClick: function() {this.onTagDelete(tag.name)}.bind(this), // BIND className: "delete"}, "\u2716")), R.td({key: "name"}, tag.name), R.td({key: "regexes"}, tag.regexes.join(", "))]); }.bind(this))) // BIND ]) } } ); So in order to preserve the this-value in the click-handler; I use bind both for the map() and the click-handler.
Is this the proper way to pass arguments to handlers in React or is there a better way?
var that = thisand use that in the handlerthat.onTagDelete. Also pass your argument in the binding.maptakes an optional second parameter that is used as the context for the function call, i.e. what "this" means. You can do.map(function() { ... }, this)instead of usingbind.