0

I have the following images in a src/assets folder of a React project.

src/assests/
     a.webp
     b.webp
     c.webp

I would like to define a functional component that is a div containing the image corresponding to its name (name is a string).

I can get it to always be 'a'

import a from "./assets/a.webp";

function ImageTile({name}){
    return <div> 
               <img src = {a}/>
           </div>
}

But if I change it to this to try and be more general then the image doesn't load correctly.

function ImageTile({name}){
    return <div> 
               <img src = {eval(name)}/>
           </div>
}

Even if this did work it seems tedious to have to import every image. I'm happy to save the images somewhere else within the react app directory.

Here is a github gist with a full App.js example if it helps people understand what I am trying to do?

https://gist.github.com/oli5679/96f4549d82b1897a91c2528a4651cd51

I have also tried the approach suggested here, but get an error

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

const images = importAll(require.context('./assets', false, '/\.webp/'));
console.log(images);
# require__(...).context is not a function
oli5679
  • 1,709
  • 1
  • 22
  • 34

0 Answers0