0

For context, I was reviewing Dynamically import images from a directory using webpack

When trying to use the importAll(i) function,

It seems that my images object does not get populated and/or the images object is undefined.

Can anyone help as to where I am going wrong?

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

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


<img src={ images['chatLogo.png'] } alt="Chat Logo" width="300" height="250" />
  

My file directory:

Directory

I've got it in the components folder as I was trying to figure out if it was my filepath that was the issue.

Dominik
  • 6,078
  • 8
  • 37
  • 61
  • Your `importAll` function doesn't `return images`, your map function does. You need to move a `}` up so the return statement is in the outer function. – ray Mar 02 '21 at 21:03
  • When the return statement is moved a } up, the images object remains empty, let images = {} –  Mar 02 '21 at 21:12
  • 1
    So maybe in addition to that problem `i.keys()` is empty? – ray Mar 02 '21 at 21:16
  • It would seem so. This would've been great to implement as I'm new to React & Javascript. –  Mar 02 '21 at 21:44

1 Answers1

0

Your importAll function doesn't return images, your map function does. You need to move a } up so the return statement is in the outer function.

Formatted for clarity, but otherwise unmodified:

function importAll(i) {
    let images = {};
    i.keys().map((item, index) => {
        images[item.replace('./', '')] = i(item);
        return images; // <-- this should be outside the map function
    });
    // return images; <-- should be here
}
ray
  • 26,557
  • 5
  • 28
  • 27