Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!