简体   繁体   中英

Javascript import set images dynamically

I am using react and trying to import images and then dynamically display them.

import DE from 'assets/flags/flag_DE.png';
import US from 'assets/flags/flag_US.png';
import GB from 'assets/flags/flag_GB.png';


const countries = [
  {
    code: DE
  },
  {
    code: GB
  },
  {
    code: US
  }
];

Then in my render method I loop over the countries and want to display the flag based on the country code.

<img src={country.code} />

the issue here is that it is setting the src as 'DE' , 'US' and 'GB'

You are passing the country code to the src , not the image path. You should look up the image in countries . I whould change the structure of countries to object (or map) to easy access images by country name. Eg:

const countries = { DE, GB, US };

<img src={countries[country.code]} />

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