Search code examples
javascriptjsonreactjssemantic-ui

Get random generated links to be different for each of the object


I have an array of objects of this form:

const myData = [
  {
    "image": "https://placedog.net/300?random",
    "name": "A",
  },
  {
    "image": "https://placedog.net/300?random",
    "name": "B",
  },
  {
    "image": "https://placedog.net/300?random",
    "name": "C",
  },
];

as you can see, the image is accessed from that randomly generated link. The problem is that I get the same image for all (3 in this case) objects. Is it a way to "pause" in some way the reading of the data so it will show a different image for each object?

I'm putting this object in state and after that, using Semantic UI's grid I'm mapping over it and show the objects on the page:

import React, { Component } from 'react';
import { Grid, Image } from 'semantic-ui-react';
import './App.css';
import dogs from './data/dogs.json'; // put the data into a json file

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dogList: dogs,
    };
  }

  render() {
    const { dogList } = this.state;

    return (
      <div className='App'>
        <Grid>
          <Grid.Row>
            {dogList.map((dog) => (
              <Grid.Column className='grid-element'>
                <>
                  <div>{dog.name}</div>
                  <Image src={dog.image} />
                </>{' '}
              </Grid.Column>
            ))}
          </Grid.Row>
        </Grid>
      </div>
    );
  }
}

export default App;

Solution

  • You can add a random query parameter to the end of each src to ensure that a subsequent network request is made for each image, rather than using the browser's cache. Another example:

    Gives duplicates:

    <img src='https://placedog.net/300?random'>
    <img src='https://placedog.net/300?random'>

    Does not give duplicates:

    <img src='https://placedog.net/300?random&foo=bar'>
    <img src='https://placedog.net/300?random&foo=barz'>

    In your code, use:

    <Image src={dog.image + '&foo=' + Math.random()} />