Have seen a couple of answers online but there are no clear explanations and the solutions don't work. So this is what I am trying to do:
- I have a folder of MANY images (thousands) - currently it is saved under
src/assets/images
folder - Given a list of images for example as input, I want to render these images dynamically. And not import all because it would be impossible given the insane number of images
This is my current way of implementing it (which does not work):
// for example
const imageList = ['img1', 'img2', 'img3' /*...so on */]
const getImagePath = (image) => {
return `../assets/images/${image}.jpg`
}
function ImagesPage() {
return (
<>
<p>Below should show a list of images</p>
{imageList.map((img) => {
return <img src={require(getImagePath(img))} />
})}
</>
)
}
From what I read online, this has something to do with the way webpack works, and this will only work if the exact string path is input into the require
:
// This works:
<img src={require('../assets/images/img1.jpg')} />
// But all these will not work:
<img src={require(getImagePath(img))} />
const img = 'img1.jpg'
<img src={require(`../assets/images/${img}`)} />
Any idea how I can get this dynamic importing of images to work in the scenario I described above? I think this post will be quite helpful to the others searching for an answer too.