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.
JavaScript
x
2
1
<Image source={require('image!avatar')} />
2
But if I change it to a dynamic string, I get
JavaScript
1
2
1
<Image source={require('image!' + 'avatar')} />
2
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?
Advertisement
Answer
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.
JavaScript
1
11
11
1
// GOOD
2
<Image source={require('image!my-icon')} />
3
4
// BAD
5
var icon = this.props.active ? 'my-icon-active' : 'my-icon-inactive';
6
<Image source={require('image!' + icon)} />
7
8
// GOOD
9
var icon = this.props.active ? require('image!my-icon-active') : require('image!my-icon-inactive');
10
<Image source={icon} />
11
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.