Why does my Javascript loop only return the first value?
I'm creating a loop in ES6 which will be used to loop through and output a sequence of 51 images. I've created a for loop, however it only returns the first image, image_0000.jpg, when it runs.
How come it's not returning all 51 images?
sequenceImages() {
for (let i = 0; i < 51; i++) {
return <img src={require(`../images/image_000${i}.jpg`)} alt="" />
}
}
Your return statement exits the function immediately during the first time through the loop. It sounds like you want it to return many <img>
tags so you can do something like this:
gitImage(i) {
return <img src={require(`../images/image_000${i}.jpg`)} alt="" />
}
sequenceImages() {
const images = [];
for (let i = 0; i < 51; i++) {
images.push(getImage(i));
}
return images;
}