Reputation: 2094
I was trying to use forEach or map functions with no success (had xxx is not a function errors). Decided to go with good old for loop but instead of creating multiple div elements my program only renders one.
Simplified example:
getTest(){
const l = this.props.renderedDrugs.length;
for(var i = 0; i < l; i++){
return <div>{this.props.renderedDrugs[i].id}</div>
}
}
render() {
const test = (this.props.renderedDrugs) ? this.getTest() : nope()
function nope(){
return 'nope'
}
return (
<div>{test}</div>
)
}
}
No matter what I do I cant return multiple divs, have no problems with multiple console logs though. Am I missing something crucial from basic react functions that I completely forgot because of staring at the screen like a moron?
Upvotes: 1
Views: 1004
Reputation: 31761
You do want map
:
getTest() {
return this.props.renderedDrugs.map(rd => <div>{rd.id}</div>)
}
The reason only one renders is because return <div>{this.props.renderedDrugs[i].id}</div>
, ya know, returns that value from the function. map
is a lot cleaner but you can emulate map with your for loop and an array:
getTest(){
const l = this.props.renderedDrugs.length;
const ary = [];
for(var i = 0; i < l; i++){
ary.push(<div>{this.props.renderedDrugs[i].id}</div>);
}
return ary;
}
Upvotes: 1