I have a list of svg files, each file containing the logo of a sports team.
Within a component I get a JSON object with the list of teams, each team has id, abbreviation, name and so forth. I want to display the logo of each team next to its name so I am importing all of the svg files into the component and giving them a variable name of abbreviation + "_Logo" and I am coding it like so:
import Abbr1_Logo from '../resources/img/team1_logo.svg';
import Abbr2_Logo from '../resources/img/team2_logo.svg';
import Abbr3_Logo from '../resources/img/team3_logo.svg';
...
let teams = result.data.map(t => {
return (
<li key={t.id}>
<img src={t.abbreviation + "_Logo"} height="50" width="50"></img> {t.full_name}
</li>
);
});
As expected the logos are not displayed I get the icon not found image next to each team name. I tried using eval like so:
<img src={eval(t.abbreviation + "_Logo")} height="50" width="50"></img> {t.full_name}
but it gave me the error:
Unhandled Rejection (ReferenceError): Abbr1_Logo is not defined
Is there a way I can accomplish this?
By the way if I hard code one of the imports into this line it works, but of course all of the teams have the same logo, so at least I know that the files are being imported correctly and that the code resolves it when the imported variable is used.
Thank you.
Your imports can not be evaluated at compile-time (when webpack / typescript are running) because the information about the teams is not know yet.
What you can do is using the copy-webpack-plugin
to copy the logos over and then use
src={`/resources/team-logos/${t.abbreviation}_logo.svg`)}
Make sure the copy-webpack-plugin copies things into the right folder, in my code it's /resources/team-logos
I think you can add your images as object and object keys can be like that
const images = {
Abbr1_Logo: "../resources/img/team1_logo.svg"
Abbr2_Logo: "../resources/img/team2_logo.svg"
}
and then you can require the image an do the concatenation on the object level like
images[`${t.abbreviation}_logo`]
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.