samedi 22 octobre 2022

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!




Aucun commentaire:

Enregistrer un commentaire