0

I'm trying to create a simple weather app. It gets an API response where weather description is represented by some string, for eg: "clear sky". I've created a JS object which maps those strings to the corresponding icon file paths which are in src/assets/images folder:

const weatherIcons = {
  // ...
  "Heavy_Rain": "../assets/images/icons8-heavy-rain-96.png",
  // ...
}

I'm trying to dynamically display that icon in my component:

<img className="img-fluid" src={require(weatherIcons.Heavy_Rain)} />

And I get the following error:

Error: Cannot find module '../assets/images/icons8-heavy-rain-96.png'

But it works perfectly if I use the string directly as a require argument:

<img className="img-fluid" src={require("../assets/images/icons8-heavy-rain-96.png")} />

I use Parcel instead of Webpack to bundle project files. And I didn't run Create React App, so I don't have Public folder in my project.

What do I do to have my icons displayed eventually?

Amit Dash
  • 584
  • 8
  • 21
Mike
  • 1
  • 1

1 Answers1

0

This is happening at runtime:

require(weatherIcons.Heavy_Rain)

This happens at compile:

require("../assets/images/icons8-heavy-rain-96.png")

So you will need a public folder for dynamic or some public link with the image.

If your homepage is set to "." and put the image in the public folder it should work.

Skar
  • 101
  • 4
  • How can I create public folder corresponding to /public url? – Mike Aug 26 '22 at 19:13
  • For parcel you can do as shown here: https://stackoverflow.com/questions/64713341/how-do-i-include-asset-files-with-parcel-js – Skar Aug 26 '22 at 19:28
  • Unfotunately, it only works out for final bundle build. Thanks anyway. – Mike Aug 26 '22 at 21:24