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
random
is already an image. ThisMath.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
random
is an image but you’re trying to use it as a number later on.