Reputation: 24308
When I am mapping through props in a components render method, can I pass in prop values to a function. I have forgotten the correct way to do this. For instance I have a category tag control which just lists some categories with a name, however onClick I want to perform some functionality for the individual category.
var React = require("react");
var CategoryTags = React.createClass({
propTypes: {
categories: React.PropTypes.array.isRequired
},
render: function() {
var categoryRows = this.props.categories.map(function (c, i) {
return (
<button onClick={ this.linkToCategory.bind(name) } >
{c.name}
</button>
);
}.bind(this));
return (
<span>{categoryRows}</span>
);
},
linkToCategory: function (c) {
console.log(c);
}
});
So in this example, while mapping though the categories, I want to pass in the name of the individual category so I can parse the link. Of course it would make sense for the object to have a link property but it didn't in this case.
Example of the categories object being passed in to the component props
categories = [{'name': 'cat1'}, {'name': 'cat2'}];
Upvotes: 0
Views: 7542
Reputation: 12430
You can also return a function from your event handler:
var CategoryTags = React.createClass({
propTypes: {
categories: React.PropTypes.array.isRequired
},
render: function() {
var categoryRows = this.props.categories.map(function (c, i) {
return (
<button onClick={this.linkToCategory(c)} >
{c.name}
</button>
);
}.bind(this));
return (
<span>{categoryRows}</span>
);
},
linkToCategory: function (c) {
return () => {
console.log(c);
}
}
});
Upvotes: 0
Reputation: 816322
Binding a function inside .map
is not a good idea, because you are always going to pass a new function to the component, even if no other prop changed. That means it will always be re-rendered, even if it doesn't have to be.
But anyways, the problem with your code is that
name
..bind
incorrectly.The call should be
this.linkToCategory.bind(this, c.name)
The first argument passed to bind .bind
is the value of this
, not the first argument (which you should know since you are using .bind(this)
as well).
You can learn more about .bind
in the MDN documentation.
Upvotes: 2