'Import multiple images on React

I'm trying to build a react app and I have to use multiple images ,now do i have to import every images i'll use like:

import image from '/img/img1.png';

<img src={img} />

or is there another way to it???,

PS: I've tried "require" and it gave an error also :

<img src={windows.location.origin +'/img/img1.png'}/>

gives no output



Solution 1:[1]

  • Since you are using webpack, have a look at require.context . You should be able to import all png files in '/img' to images variable. Then you can use image by images["img(n).png"].
function importAll(r) {
    let images = {};
    r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
    return images;
}

const images = importAll(require.context('/img', false, '/\.jpg/'));

<img src={images["img1.png"]} />
  • In another way, you can use a file dedicated to these imports :

images.js :

import img1 from "/img/img1.jpg"
import img2 from "/img/img2.jpg"
import img3 from "/img/img3.jpg"
.
.
.
import img(n) from "/img/img(n).jpg"

export default [
    img1,
    img2,
    ...
];

Then import this array in one line in other files :

import imgs from './images';

P.S. please refer my accepted answer on similar question.

Solution 2:[2]

If you're using ES6+, you can use iteral. Something like below.

const imageNames = ['img1.jpg', 'img2.jpg', 'img3.jpg']
render() {
  ...
  imageNames.map(image => <img src={`/img/${image}`}></img>)
  ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 koko-js478
Solution 2 baymax