0

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!

1 Answer 1

1

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`)} />
Sign up to request clarification or add additional context in comments.

1 Comment

Worked like a charm, thanks! For anyone reading in the future, @user11877521 was correct in assuming my images are stored in the src folder for this use-case :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.