Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
What is the correct syntax inside the src property in a img tag for a mapped json file using ReactJS?

I want to import some images from a local JSON file to my component. I want them to match with the data that I fetch from the API.

My JSON file is:

[
  {
    "id": 1,
    "dwarf": "/assets/races/dwarf.png",
    "slug": "dwarf"
  },
  {
    "id": 2,
    "elf": "/assets/races/elf.png",
    "slug": "elf"
  }
]

I have this for mapping the JSON file:

                {images.map((item, index) => (
                    <C.Image
                        key={index}
                        item={item}
                    >
                        <img src={`item.${data.slug}`} />
                        <img src={item.dwarf} />
                    </C.Image>

{data.slug} is fetched from the API and matches the property name that I pass to each image inside the JSON file. When I insert <img src={item.dwarf} />, I have the image displayed, but it is the same for all. When I insert <img src={`item.${data.slug}`} />, the image is not displayed and at the console it shows <img src="item.dwarf"> <img src="item.elf">, instead of the image. What is the syntax to make use of the {data.slug} replacing each name and displaying the image?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use bracket notation to dynamically access object properties. It looks like this:

const obj = { foo: 123, bar: 321 }

const propName = 'foo'
const prop = obj[propName]

console.log(prop) // output: 123

So in your case:

<img src={item[item.slug]} />
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda