1

I stored images locally in project folder, and I want to add a variable (nature.png) inside image source (with require), so I did like this

let i = 'natrue';
let imagePath = require('../asset/gallery/image/');
    return (
        <View >
            <Image source={{imagePath} + i + '.png'}/>
        </View>

But I got an error:

text string must be rendered within a text component

And I dont want to do like this (Works fine) because I have more than 100 images:

<Image source={require('../asset/gallery/image/nature.png')} />
HowardJohn
  • 51
  • 9
  • Maybe try and use `imagePath + i + '.png` instead (without the `{}` around imagePath) – Nick Parsons Sep 19 '20 at 13:15
  • @NickParsons I got same error – HowardJohn Sep 19 '20 at 13:20
  • ReactNative's `` component's `source` prop has a type of `ImageSourcePropType`, not a String like you're trying pass it. You could try using [this](https://stackoverflow.com/a/50757738/5648954) idea by passing an object with a `uri` or, you could stick with require and change the string: `require('../asset/gallery/image/' + i +'.png')` – Nick Parsons Sep 19 '20 at 13:34
  • @NickParsons I got an error Unable to resolve module – HowardJohn Sep 19 '20 at 14:07

1 Answers1

1

Unfournately requirejs module doesn't work that way

You'll have to create strings completely or create a object which will map a key to image. Also that is a best practice to follow.

you can create a file called image.js and export all your images from there,

for example

// image.js

const BASE_URL = "../asset/gallery/image/";

export default {
  nature:require(`${BASE_URL}nature.png`),
}

and in your components,

import Images from "src/images";

...
<>
   <Image src={Images.nature}/>
</>
...

senthil balaji
  • 588
  • 4
  • 18