Braxton Goss
Braxton Goss

Reputation: 23

Selecting correct Image source based on random integer generation

I have a list of images I want to use for a project. I would like to have it select a new image each time the page reloads out of that original list of images.

Is there a more scalable way to do this without explicitly assigning the source in each switch-case?

import greeting from "../images/memoji/image1.png";
import coding from "../images/memoji/image2.png";
import lightbulb from "../images/memoji/image3.png";

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1) + min);
}

const randomInt = getRandomIntInclusive(1, 3);
let source;

switch (randomInt) {
  case 1:
    source = greeting;
    break;
  case 2:
    source = coding;
    break;
  case 3:
    source = lightbulb;
    break;
  default:
    source = greeting;
}

 <img src={source} />

Any help would be greatly appreciated!

Upvotes: 0

Views: 29

Answers (1)

user11877521
user11877521

Reputation: 331

What you could do here to get rid of switch is use a template string as follows. Here i am assuming "./image1.jpg" "./image2.jpg" are in src folder

    function getRandomIntInclusive(min, max) {
      min = Math.ceil(min);
      max = Math.floor(max);
      return Math.floor(Math.random() * (max - min + 1) + min);
    }
    
    const randomInt = getRandomIntInclusive(1, 2);
   <img src={require(`./image${randomInt}.jpg`)} />

Upvotes: 1

Related Questions