I'm currently mapping over a prop like so:
renderList(item) {
return(
</div>
shows up
</div>
)
}
render() {
return(
<div>
{this.props.items.map(this.renderList)}
</div>
);
}
}
I have another prop I would like to pass
this.props.completed
A simplified version of what I would like to do
renderList(item, completed) {
return(
</div>
shows up
</div>
)
}
render() {
return(
<div>
{this.props.items.map(this.renderList(this.props.items, this.props.completed)}
</div>
);
}
}
Is it possible to pass another prop with this map function?
There are (at least) 3 ways to go about this. The simplest is to bind renderList
to your component instance and reference this.props.completed
within it:
constructor (props) {
super(props);
// it's more efficient to bind your functions once in the constructor than
// doing so on every render
this.renderList = this.renderList.bind(this);
}
renderList(item) {
const completed = this.props.completed;
return(
<div>
shows up
</div>
)
}
render() {
return(
<div>
{this.props.items.map(this.renderList)}
</div>
);
}
Another option is to use a closure to pass the property into the function:
renderList(completed, item) {
return(
<div>
shows up
</div>
)
}
render() {
const completed = this.props.completed;
const renderList = this.renderList;
return(
<div>
{this.props.items.map(function (item) {
return renderList(completed, item);
})}
</div>
);
}
A third option would be to bind the property to the map()
callback.
renderList(completed, item) {
return(
<div>
shows up
</div>
)
}
render() {
return(
<div>
{this.props.items.map(this.renderList.bind(this, this.props.completed))}
</div>
);
}