Importing multiple files in react

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.


I think maybe a better idea is to use an index file for your images folder.

Supposing you have this structure:

Initial folder structure, where all images are on subfolders inside assets/images

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: Final folder structure where we have an index.js inside assets/images

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
};

I'm not sure it's really a good way but i was also looking for how to import several images to Components. however, I wanted to import images like a module

image folder

  • a.png
  • b.png
  • c.png
  • index.js

index.js

import a from "./a.png";
import b from "./b.png";
import c from "./c.png";
const images = {
    a,
    b,
    c
}
export default images;

Component which images imported

import images from './images'; //Your images folder location

Usage in the render()

render(){
    return(
         <img src={images.a} />
    )
}