Reputation: 25
I am making a random image generator, which needs to display 14 random images. This works, however those 14 random images are being replaced with others 3 times in a call.
I don't want this to happen, but I have no clue on how to stop this. I think that math.random() is causing the issue, but I'm not sure. I am running this script on React.JS
My code:
for (var g=0; g < 14; g++) {
var rdmNumber = Math.floor(Math.random() * 14) + 1;
var imgName = "img_" + rdmNumber +".png";
var src = "img" + "/" + imgName;
indents.push(<div className="item-picture" key={c}><img src= {src8}className="item-img" alt="Your possible winnings" /></div>);
}
The indents.push is the output of my call, which is being displayed as followed:
{indents}
.gif from what is happening: https://gyazo.com/c576c52a90843a9ab055790610303fe4
Thanks in advance.
EDIT I don't need unique images, I just want them to stay the same, and not replace as seen in the .gif
Upvotes: 0
Views: 1120
Reputation: 2756
What you want is create an array of random images once, outside of render, and then render that.
Do it outside of the component, or in the constructor.
// outside of your component
let images = []
for (var g=0; g < 14; g++) {
var rdmNumber = Math.floor(Math.random() * 14) + 1;
var imgName = "img_" + rdmNumber +".png";
var src = "img" + "/" + imgName;
images.push(src);
}
// in your component's render method
images.forEach(url =>
indents.push(<div className="item-picture" key={url}>
<img src= {url}className="item-img" alt="Your possible winnings"/>
</div>)
)
// and you can render {indents} somewhere after that
Upvotes: 0
Reputation: 1033
You might have written this code inside render function which will run every time there is some change.
Try to write this code in componentWillMount.
Upvotes: 1