0

Is there a way to do something like that in React Native :

<Image source={require("../../../assets/imgList/" + this.props.imgName + ".png")} />

I got this error:

'require' expect exactly 1 string literal argument.

Thank you.

c-chavez
  • 7,237
  • 5
  • 35
  • 49
GuillaumeRZ
  • 2,656
  • 4
  • 19
  • 35
  • here: https://stackoverflow.com/questions/47887697/require-must-have-a-single-string-literal-argument-react-native – Hoàng Vũ Anh Nov 22 '18 at 10:32
  • No, this is not exactly solving my problem. I already found the documentation, but I do not want to write every single path to my images, and this is not a simple boolean but a big big list. – GuillaumeRZ Nov 22 '18 at 10:35
  • Then you should offload this path generation to a separate method and invoke that to retrieve the final string. – Easwar Nov 22 '18 at 10:41
  • I tried to do so but I got the same error. I mean call a method that will generate my string (let's say iconPath) then you call require(iconPath). – GuillaumeRZ Nov 22 '18 at 10:43
  • `require()` resolves your path at compile time before your app even runs. So you can't pass it a string that can only be resolved at run time. It must be a string literal. – trixn Nov 22 '18 at 10:53
  • So this is completely impossible @trixn ? Thank you for the explications. – GuillaumeRZ Nov 22 '18 at 10:54
  • 1
    @Gouigoui I'm not exactly sure. Webpack is able to do that. I believe that react-native uses the metro bundler which can only resolve that at compile time. The problem is that this kind of statement needs to be transformed into code that actually fetches the missing file when your application runs because only then the path is known. I think this is, what webpack does. So it is not trivial. The transpiler must replace that call to `require` with some kind of loader that actually knows how to get that image. If the path would be known before, the image can simply be bundled into the app. – trixn Nov 22 '18 at 11:01
  • 1
    @Gouigoui Also see [Network Images](https://facebook.github.io/react-native/docs/images#network-images) in the react-native docs for alternatives. – trixn Nov 22 '18 at 11:05

0 Answers0