Home > Mobile >  Dynamic src for img tag with javascript
Dynamic src for img tag with javascript

Time:01-30

I have a react-app that gets crypto API from some Provider Server and setState in currency variable and shows them in a table. I download each cryptocurrency icon and create a JSON file (cryptoIconSrc) to set img tag src dynamically. icons are SVG. but they don't display on my table.

here I set a condition to find the related icon from the JSON file

currency.map((item) => {
                    let mapItem = item;
                    const temp = cryptoIconSrc.filter((item) => {
                      return item["symbol"] === mapItem["baseAsset"];
                    });

and here I set that related icon to img src

                    <img
                    src={`${temp[0]["src"]}`}
                    width="20px"
                    height="20px"
                    />

but they don't display

I use require("./someDirectory/icon.png") in other sections of my app but in this case require(`${temp[0]["src"]}`) doesn't work and issue an error : module ... not found

CodePudding user response:

  <img
    src={`${temp[0]["src"]}`}
    key={`${temp[0]["src"]}`}
    width="20px"
    height="20px"
   />

Adding a key prop will do the trick.

CodePudding user response:

It seems like you are using back ticks in your code. That almost never works, try using single quotes. So not:

src={`${temp[0]["src"]}`}

But:

src={'${temp[0]["src"]}'}
  •  Tags:  
  • Related