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)
Import Limitations in React There is a key import limitation in React which we haven't discussed thus far: you cannot import from files outside the src directory.
Introduction. Importing and exporting in React JS will help us write modular code, i.e., splitting code into multiple files. Importing allows using contents from another file, whereas exporting makes the file contents eligible for importing.
I think maybe a better idea is to use an index file for your images folder.
Supposing you have this structure:
And you need to import all of your images to your HomePage component. You can easily create an index.js
file on your images folder, exporting all the images using require, like this:
export const Background = require('./bg/background.jpg'); export const First = require('./photos/first.jpg'); export const Second = require('./photos/second.jpg'); export const LinkedIn = require('./social/linkedin.png');
Then on your component you can import all of them with a single import.
import { Background, First, Second, LinkedIn } from '../../assets/images'
And this would be your final folder structure:
Hope it helps! ;)
Updated on 25/04/2021:
If you want to use ES6 named imports:
images/index.js:
import Background from './bg/background.jpg'; import First from './photos/first.jpg'; import Second from './photos/second.jpg'; import LinkedIn from './social/linkedin.png'; export { Background, First, Second, LinkedIn };
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With