Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
react load grid of images based on name

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
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda