Saturday, May 11, 2024
71
rated 0 times [  75] [ 4]  / answers: 1 / hits: 180837  / 9 Years ago, mon, june 15, 2015, 12:00:00

I'm currently building a test app using React Native. The Image module thus far has been working fine.


For example, if I had an image named avatar, the below code snippet works fine.


<Image source={require('image!avatar')} />

But if I change it to a dynamic string, I get


<Image source={require('image!' + 'avatar')} />

I get the error:



Requiring unknown module image!avatar. If you are sure the module is there, try restarting the packager.

Obviously, this is a contrived example, but dynamic image names are important. Does React Native not support dynamic image names?


React


More From » react-native

 Answers
46

This is covered in the documentation under the section "Static Resources":



The only allowed way to refer to an image in the bundle is to literally write require('image!name-of-the-asset') in the source.



// GOOD
<Image source={require('image!my-icon')} />

// BAD
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
<Image source={require('image!' + icon)} />

// GOOD
var icon = this.props.active ? require('image!my-icon-active') : require('image!my-icon-inactive');
<Image source={icon} />

However you also need to remember to add your images to an xcassets bundle in your app in Xcode, though it seems from your comment you've done that already.


http://facebook.github.io/react-native/docs/image.html#adding-static-resources-to-your-app-using-images-xcassets


[#66196] Friday, June 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tatyanna

Total Points: 552
Total Questions: 96
Total Answers: 96

Location: Cook Islands
Member since Thu, May 21, 2020
4 Years ago
tatyanna questions
;