Reputation: 45
My loop repetition does not work, I'm using React to render on the screen, but only one element appears and my array has 12 elements. Can someone tell me why?
import React from 'react'
import '../custom/style.css'
export default props =>{
const renderRows = () =>{
const list = props.list || []
for (var i = 0; i < list.length; i++) {
var obj = list[i];
return (
<div key={obj.id}>
<p>{obj.title}</p>
<img src={obj.images.normal} />
</div>
)
}
}
return(
<div id="demo">
{renderRows()}
</div>
)
}
Upvotes: 0
Views: 3265
Reputation: 71
Mapping over the div
s is easier. The loop return
s after the first iteration, thus only one <div>
.
import React from 'react'
import '../custom/style.css'
export default rows = () => {
return (
props.list && props.list.map(obj => {
<div key={obj.id}>
<p>{obj.title}</p>
<img src={obj.images.normal}/>
</div>
})
)
}
Upvotes: 0
Reputation: 46
You're returning a <div>
on the first loop iteration. You'll want to create an array and push all your elements there instead. I'd recommend using the map
function i.e.
const renderRows = () => {
const list = props.list || [];
return list.map(obj => (
<div key={obj.id}>
<p>{obj.title}</p>
<img src={obj.images.normal} />
</div>
));
};
Upvotes: 2