Search code examples
javascriptimagereact-nativerequire

Error using require with react native in JavaScript


I'm trying to do this:

<Image source={require(`../../imagens/cards${result.color}.png`)}/>

in that path I have 5 png files: cardsgreen, cardsyellow, cardspurple,...

result.color gives me an string which is purple and it doesn't work because require doesn't allow it and I want to know if there is another way to do it, I have also tried:

source={{ uri: `../../imagens/cards${result.color}.png` }}

and it didn't work either, the image just didn't open in that case

error: The development server returned response error code: 500, calls to require expect exactly 1 string literal argument


Solution

  • try yo use:

      var images = {
                    blue: require('../imageblue.png'),
                    red: require('../imagered.png')
                }
    <Image source={images[this.state.imgColor]} key={images[this.state.imgColor]} />
    

    ImgColor should be your result.color. Don't forget to use key on image, else the state will not change the color it dynamically.