Reputation: 35
Here, I'm trying to show images and titles depending on the value of num. Since the index from 0-4 is supposed to have random images, when I press the next button, the title changes but the images remain the same it doesn't update. How do I map this in a way that every time I press the next button, the different images come?
export default class MainContainer extends Component {
constructor() {
super();
this.state = {
posts: [
{
"title": "Title 1",
"image": "https://source.unsplash.com/random"
},
{
"title": "Title 2",
"image": "https://source.unsplash.com/random"
},
{
"title": "Title 3",
"image": "https://source.unsplash.com/random"
},
{
"title": "Title 4",
"image": "https://source.unsplash.com/random"
},
{
"title": "Title 5",
"image": "https://source.unsplash.com/random"
},
{
"title": "Title 6",
"image": "https://www.instagram.com/static/images/ico/apple-touch-icon-76x76-precomposed.png/4272e394f5ad.png"
}
],
num : 0,
}
}
nextPic = () => {
if(this.state.num > 4) {
this.setState({
num : 0
})
} else {
this.setState({
num : this.state.num + 1
})
}
}
render() {
return(
<div>
<h1>{this.state.posts[this.state.num].title}</h1>
<img src={this.state.posts[this.state.num].image} />
<button onClick={this.nextPic}>Next</button>
</div>
)
}
}
Upvotes: 1
Views: 54
Reputation: 1318
You need to change the url in some way in every call for react to detect change and re-render a new image. One way to do it is append a query with a random integer to the url.
For eg:-
getImageSource() {
const randomNumber = Math.floor(Math.random() * 10);
return `https://source.unsplash.com/random?${randomNumber}`;
}
Working example:- https://codesandbox.io/s/z30qom5m8x?fontsize=14
Upvotes: 1
Reputation: 4299
It is not a ReactJS problem. If you will have a normal paths to images, and they will be different everything will render properly with different images.
Somehow unsplash and picsum return same images when you iterate with their random paths.
Upvotes: 0