简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM