React click handlers and bind this

I have a react component where I iterate over a list and create strings. Each line has a delete button. When the delete button is clicked, I want to pass a link to the item on that line.

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, to store this value in the click handler; I am using bind for both map () and click handler.

Is this the correct way to pass arguments to handlers in React, or is there a better way?

+3


source to share


2 answers


I'm brand new to react, but I figured I'd drop this here to help.

I think you need to change this line,

R.td({}, R.button({onClick: function() {this.onTagDelete(tag.name)}.bind(this), // BIND
                            className: "delete"}, "\u2716")),

      



to

R.td({}, R.button({onClick: function() {this.onTagDelete.bind(this, tag.name)}, // BIND
                            className: "delete"}, "\u2716")),

      

I'm sure this name is now being passed to the function. Another way to get data from the clicked object is via links, but with lists of items I don't think this works well because of the duplicate link names. So I'll just do what you are doing now.

+3


source


You can do less detail:



 R.td({}, R.button({onClick: this.onTagDelete.bind(this, tag.name), // BIND
                                className: "delete"}, "\u2716")),

      

+1


source







All Articles