1

I am currently working on a React + Redux Project and wanted to use language messages to render an image.

The problem is that, because the image name is dynamic (because of the language switching), I can't use require(imageVar) to load the image.

What I currently am working with is this (this is inside of the render() function):

FormattedMessage {...messages.fullLogo}>
        {
          (fullLogo) => <Img src={require(`${fullLogo}`)} alt="Banner" />
        }
</FormattedMessage>

This should theoretically load the image from the url (yes fullLogo is a full url to the image).

What I tried inside of src={} was:

require(`${fullLogo}`)
require(fullLogo)
require("" + fullLogo)
require(String(fullLogo))
require(fullLogo.toString())

Everytime I try one of these (except the 3rd one - gives me an fatal error) I get an "Could not Load Module './img/image.png'" error.

I guess this means, that the name does load but require somehow cannot access the variable.

However if i put the path directly into the require() function. It successfully loads the image.

I don't want this though. I want it to load it dynamically.

Maybe you guys have some experience with it.

Thanks in advance!

PS: If you need any extra code, let me know!

Shai Shvili
  • 99
  • 1
  • 1
  • 6

1 Answers1

0

You can't dynamically require files by variable at runtime, since require happens before runtime, when you bundle your app together (e.g. using webpack).

Based on how the packager works, this isn't really possible with require. Packaging happens once before runtime so those variables don't have values yet.

What do you mean by langage switching ? What does message.fullLogo contains ? If it contains an url, just use that url without require:

Saraband
  • 1,540
  • 10
  • 18
  • Using url instead of require also needs the images to be moved to the public folder rather than the source folder, which probably requires a little bit of whichever builder OP uses configuration. – nubinub Feb 27 '19 at 10:33