skip to Main Content

So I have created a Json file with ID’s and images of famous people. Now I would like to get a single random image out of the Json file and display it.

SO far I tried this, but I get an "Uncaught TypeError: Cannot read properties of undefined (reading ‘image’).

import images from "../Index.json"

function Celeb() {
  const [image, setImage] = useState();
  let random = images[Math.floor(Math.random() * images.length)];


    const handleNext = () => {
      console.log(images[1].image);
      setImage(images[random].image);
    }
    

  return (
    <div className='celeb'>
      <div className='celeb_buttons'>
        <button className='play_button' onClick={handleNext}>Next</button>
   
      </div>
      <div className='pic'>
        <img src={image} />
      </div>
     </div>

If I replace the random in setImage(images[random].image) with 0 for example, I get the first image element out of the Json file, but I can not do it with random.

2

Answers


  1. random is already an image. This Math.floor(Math.random() * images.length) part generates a random index.

    I don’t see the structure of your json file, but I guess you have to change the setting part to

    setImage(random.image);
    
    Login or Signup to reply.
  2. random is an image but you’re trying to use it as a number later on.

    import images from "../Index.json"
    
    function Celeb() {
      const [image, setImage] = useState();
    
      const handleNext = () => {
        // Generate a random index in the images array
        let random = Math.floor(Math.random() * images.length);
    
        // Use the random index to access the correct object in the images array
        // and set the image state to the value of the image property
        setImage(images[random].image);
      }
    
      return (
        <div className='celeb'>
          <div className='celeb_buttons'>
            <button className='play_button' onClick={handleNext}>Next</button>
       
          </div>
          <div className='pic'>
            <img src={image} />
          </div>
         </div>
      )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search