I'm making a small react application to traverse all images present in my directory. I want to change image when button is clicked. The problem is image won't load on the web.
When I'm using import method to import images then it is working fine, but I think this approach is not good when I have multiple images to work with.
I also used require() but even in this case image won't load. I don't know what's the problem.
import React from 'react'
const MyCollection = [
{
id:0,
path:"./images/0.jpg",
},
{
id:1,
path:"./images/1.jpg",
},
{
id:2,
path:"./images/2.jpg",
},
{
id:3,
path:"./images/3.jpg",
},
];
export default function App() {
const [index, setActiveStep] = React.useState(0);
const goToNextPicture = () => {
setActiveStep((prevActiveStep) => prevActiveStep 1);
};
return (
<div>
<img src={MyCollection[index].path} height={200} width={200} alt=""/>
<br/>
<input type="button" onClick={goToNextPicture} value="Next"/>
</div>
)
}
Thank You!
CodePudding user response:
Your logic is correct. You just don't have images in your local environment.
You just need create the images folder and add the images locally.
I tested it with image links, it works fine.
Sandbox link
import React from "react";
const MyCollection = [
{
id: 0,
path:
"https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1200px-Image_created_with_a_mobile_phone.png"
},
{
id: 1,
path:
"https://images.unsplash.com/photo-1453728013993-6d66e9c9123a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8M3x8Zm9jdXN8ZW58MHx8MHx8&w=1000&q=80"
},
{
id: 2,
path: "https://www.industrialempathy.com/img/remote/ZiClJf-1920w.jpg"
},
{
id: 3,
path:
"https://helpx.adobe.com/content/dam/help/en/photoshop/using/convert-color-image-black-white/jcr_content/main-pars/before_and_after/image-before/Landscape-Color.jpg"
}
];
export default function App() {
const [index, setActiveStep] = React.useState(0);
const goToNextPicture = () => {
setActiveStep((prevActiveStep) => prevActiveStep 1);
};
return (
<div>
{MyCollection[index] && (
<>
<img
src={MyCollection[index].path}
height={200}
width={200}
alt="images"
/>
<div>{MyCollection[index].id}</div>
</>
)}
<br />
<input type="button" onClick={goToNextPicture} value="Next" />
</div>
);
}
CodePudding user response:
If you want load image from your local folder, then you need to import images
Images.js
------------
import Img1 from '../images/1.jpg';
import Img2 from '../images/2.jpg';
import Img3 from '../images/3.jpg';
const list = {
Img1,
Img2,
Img3
}
export default list;
Main.js
----------------
import list from './images';
<img src={list.Img1} />
<img src={list.Img2} />
<img src={list.Img3} />