How do I dynamically import images in React?
Adding .default will do the trick
<img src={require(`../../folder-path/${dynamic-filename}.png`).default} />
TLDR;
// All of these worksconst fileNameExt = 'foo.jpg'<img src={require('../images/' + fileNameExt)} /><img src={require(`../images/${fileNameExt}`)} />const fileName = 'foo'<img src={require('../images/' + fileName + '.jpg')} /><img src={require(`../images/${fileName}.jpg`)} />// These does not work:const myPathVariable1 = '../images/' + 'foo' + '.jpg'<img src={require(myPathVariable1)} />const myPathVariable2 = '../images/' + 'foo.jpg'<img src={require(myPathVariable2)} />
You can require dynamically with expression.
File names:
const imageList = ["img1", "img2", "img3", ... ]
And to render at UI (add directory path and the extension inside require
):
{ imageList.map(img => { return <img src={require("../assets/images/" + img + ".jpg")} /> })}
Why it works?:
Webpack can understand this expression, by generating context about directory and extension, and can load all the matching modules.
Update your getImagePath
function to return an img
element.
const getImage = (image) => { return <img src={require(`../assets/images/${image}.jpg`)} />}
Then your map
function would look like this:
imageList.map((img) => { return getImage(img);});