I am trying to build a dynamic application. When you click on the picture it should change to a different picture. Therefore I stored the src paths in an array called arrays. Then for the image instead of hardcoding the imagepath I tried using the name of the array ‘arrays’ and the position of the path I want. However both of the pictures are not loading and I don’t understand why.
I tried using require already but it didn’t work either. Maybe someone knows why it dosen’T work?
Thanks.
I also asked chat gpt to code me an example of how to output the images dynamically and it coded this:
> import React,{useState} from 'react';
> import './Secondphoto.css';
> //import ImageArray from './ImageArray.js';
>
> const Secondphoto = (props) => {
> const arrays = ["../images/mantelfrau.jpg", "../images/whitewoman.jpg", "../images/arraypicthree.jpg", "../images/arraypicfour.jpg", "../images/arraypicfive.jpg","../images/arraypicsix.jpg"]
> const [clicked, setClicked] = useState(false);
> console.log(clicked);
> const selectedImageIndex = 1;
> const selectedImageURL = arrays[selectedImageIndex];
> return(
> <div className="flex_container_secondphoto">
> <img src={selectedImageURL} alt="woman wearing something white" className="secondphoto" onClick= {() => setClicked(true)}/>
> </div>
> )
> }
>
> export default Secondphoto;
but it didn’t work either.
2
Answers
Use Usestate for both array of images and index
here
(selectedImageIndex + 1) % imageArray.length
loop over all the images in the arrayto make this work u need to do some changes.
first, you’r
SecondPhoto
should look like this:and the component that contain the image will look: