Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  1] [ 3]  / answers: 1 / hits: 64839  / 7 Years ago, sat, june 17, 2017, 12:00:00

I am using create-react-app for my react project. It has got webpack configured for importing images. I wish to import multiple images (say 10) from a images folder into a component. The easiest way of doing this would be to add multiple import statement such as -



import Img0 from '../images/0.png';
import Img1 from '../images/1.png';
import Img2 from '../images/2.png';
import Img3 from '../images/3.png';
import Img4 from '../images/4.png';
import Img5 from '../images/5.png';
import Img6 from '../images/6.png';
...


The above code would not be a good choice when we have multiple files to import. Is there a way to add the import statements in a loop? I tried adding for loop but I was unable to modify the variables Img0, Img1 etc. (using ES6 `` didn't work as it converted the variable to a string)


More From » reactjs

 Answers
4

You can't use a single import statement, because the whole point of import and export that dependencies can be determined statically, i.e. without executing code, but you can do this:


function importAll(r) {
let images = {};
r.keys().map(item => { images[item.replace('./', '')] = r(item); });
return images;
}

const images = importAll(require.context('./images', false, '/.png/'));

<img src={images['0.png']} />

Source.


[#57410] Thursday, June 15, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kurtisl

Total Points: 559
Total Questions: 110
Total Answers: 97

Location: Tokelau
Member since Sun, May 7, 2023
1 Year ago
kurtisl questions
;