Home > Software engineering >  What is the correct syntax inside the src property in a img tag for a mapped json file using ReactJS
What is the correct syntax inside the src property in a img tag for a mapped json file using ReactJS

Time:11-01

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?

CodePudding user response:

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]} />
  • Related