1

I'm trying to get some data from my state passed down into this img src url, and I can't seem to figure how to write it. I've tried using back ticks and the dollar sign. I assume because I'm down in the render part of the Component that won't work. Help me Obi-Wan, you're my only hope.

<img src={'https://openweathermap.org/img/w/{data.weather.icon}.png'} alt='weather condition' />
Scott Ladd
  • 31
  • 3
  • refer this https://stackoverflow.com/questions/54033765/how-to-give-image-src-dynamically-in-react-js If it will not help you, I suggest you add your component code also for better understanding – bajran Feb 27 '20 at 04:56

2 Answers2

1

Just like with vanilla JS, you have to use a Template Literal and use string interpolation to place your JS within the string (with a ${...}) like so:

<img src={`https://openweathermap.org/img/w/${data.weather.icon}.png`} alt='weather condition' />
Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33
1

you can use Template Literal

<img src={`https://openweathermap.org/img/w/${data.weather.icon}.png`} alt='weather condition' />
Amit Chauhan
  • 6,151
  • 2
  • 24
  • 37
  • I tried that already, it doesn't work. That's what I was referring to when I mentioned the back ticks and the dollar sign. I don't why its not working. Is that the only way to go about it? – Scott Ladd Feb 27 '20 at 04:54
  • 1
    you can still use the old way to template concatenation using `+` operator like `'https://openweathermap.org/img/w/' + data.weather.icon + '.png'` But i want to understand why that didn't work as it should work. can you share same for what is there in `data.weather.icon`? – Amit Chauhan Feb 27 '20 at 04:57
  • The first thing I tried was the + operator but I was getting errors from VS Code, it didn't like it. I know I was writing it correctly because it was how I inserted data from my state when I did my api call earlier in my code. The information that's in `data.weather.icon` is `"03n"` – Scott Ladd Feb 27 '20 at 05:06
  • I figured it out. What you wrote did work. I forgot the icon string was in an array. That was my mistake. Thank you! – Scott Ladd Feb 27 '20 at 05:52
  • @ScottLadd what was that mistake if you don't mind sharing? – Amit Chauhan Feb 27 '20 at 12:37
  • 1
    Oh, it was like I said. I forgot that that the information I was trying to get to was in an array so I just needed to add that to the path `data.weather[0].icon`. It hit me when I was looking at the error I was getting from react on the browser that said "Cannot read undefined of .png" – Scott Ladd Feb 27 '20 at 15:28