Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import all images from a folder in ReactJS? [duplicate]

I want to import all images from a folder and want to use as needed. But can't do it by following methods. What I am doing? this:

import * as imageSrc from '../img';
let imageUrl = [];
    imageSrc.map(
    imageUrl.push(img) 
    )) 

I am getting this error in console.log

index.js:1452 ./src/components/Main.jsx
Module not found: Can't resolve '../img' in 'G:\Projects\Personal\Portfolios\Portfolio_Main\React_portfolio\portfolio\src\components'

Folder Structure:

src>
  components>
    Main.jsx
  img>
    [all image files]
like image 920
Chetan Kumar Avatar asked Dec 13 '18 13:12

Chetan Kumar


1 Answers

This is not possible in plain javascript because import/export are determined statically.

If you are using webpack, have a look at require.context . You should be able to do the following:

function importAll(r) {
  return r.keys().map(r);
}

const images = importAll(require.context('./', false, /\.(png|jpe?g|svg)$/));

ref: https://webpack.js.org/guides/dependency-management/#require-context

like image 163
Mosè Raguzzini Avatar answered Sep 30 '22 01:09

Mosè Raguzzini