function importAll(r) {
let images = {};
r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
return images;
}
const images = importAll(require.context('./images', false, /.(png|jpe?g|svg)$/));
<img src={images['doggy.png']} />
<img src={process.env.PUBLIC_URL + '/yourPathHere.jpg'} />
<img src={window.location.origin + '/yourPathHere.jpg'} />
<img src={process.env.PUBLIC_URL + '/yourPathHere.jpg'} />
<img src={window.location.origin + '/yourPathHere.jpg'} />
// Original answer by Kind Kouprey, additional comments and integer index alternative by me.
function importAll(r) {
//// Use these line if you like to access arrays using an integer index.
//let images = [];
//r.keys().map((item, index) => { images.push(r(item)); });
////Use these line if you want to access each image using the file name.
//let images = {};
//r.keys().map((item, index) => { images[item.replace('./','')] = r(item); });
return images;
}
//Param 1: The path or route to the directory you want to import.
//Param 2 (optional): Include directories?
//Param 3 (optional): Use a regular expression (regex) such as "/.(png|jpe?g|svg)$/" to select only certain file types.
const images = importAll(require.context('./images', false, /.(png|jpe?g|svg)$/));
//The index can be up to the number of images in the folder - 1;
<img src={images[0]} />
<img src={images[3]} />
//Or if you used the file name method...
<img src={images["doggy.png"]} />
img elements must have an alt prop, either with meaningful text, or an empty string for decorative images