react-native icon indicating copy to clipboard operation
react-native copied to clipboard

Setting <Image /> source with string concatenation fails ('Requiring unknown module...')

Open gavinsmith opened this issue 11 years ago • 31 comments

I've seen this mentioned before: https://github.com/facebook/react-native/issues/282#issuecomment-96908438

I'm trying to include an image from within the project, the name of which is dependant on variables.

var imageName = `image!${var1}_of_${var2}`
contents = (
  <Image source={require(imageName)} style={styles.card} onPress={this._onPress} />
)

The above fails with the usual:

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

These also fail in the same manner:

<Image source={require(image!${var1}of${var2})}> <Image source={require('image!' + {var1} + '_of_' + {var2})} >

This works, no problem:

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

I've also tried

  • Stop and re-build Xcode project
  • Restarting the packager

gavinsmith avatar Aug 28 '15 14:08 gavinsmith

Right, there's an easy solution here, I don't think this is actually a bug.

source={{ uri: imageName }}

gavinsmith avatar Aug 28 '15 14:08 gavinsmith

We intentionally don't support dynamically generated image names because it makes it very hard to manage assets over time, just like how you wouldn't want to do

var MyComponent = require('./' + libName + typeOfComponent);

or something like that. Dynamic image name generation like this also won't work with the new dynamic asset managing system we're rolling out which let's you add and update assets on the fly with just cmd+R (no more need to add to Xcode and recompile).

sahrens avatar Sep 05 '15 18:09 sahrens

Question regarding the suggestion of @gavinsmith:

I was not aware you can do this for static image resources. What are the disadvantages of using { uri: "imageName" } instead of require("image!imageName")?

Thegaram avatar Oct 14 '15 10:10 Thegaram

this 'feature' is retarded and is annoying. Would very much be interested how i can bypass this stupid check

WHILE i agree that it is a good idea to stop developers from including images which consist of concatenated strings, it is the developer's responsibility to code in such way that won't cause him trouble in the future. A much better solution for react-native would be to print a notice to the console alerting them of what they just done.

matejkramny avatar Nov 29 '15 23:11 matejkramny

@matejkramny

The images need to be able to statically analyzed, so that the packager could resolve them and package in the app automatically. Hence dynamic strings with require syntax is not possible.

It's the same as bundling JavaScript with browserify or webpack. Your JavaScript filenames need to be statically analyzed and bundled.

If you want to use dynamic strings, you sure can. But you've to manually package up the assets. You can use the following syntax.

<Image source={{ uri: "image" + "name" }} />

satya164 avatar Nov 30 '15 00:11 satya164

@satya164 I am not talking about images here.

React-native is using node.js, so i'm organising my code a bit like i do on server apps.

directory tree:

.
├── commonStyles.js
├── img
│   └── logo.png
├── network.js
├── storage.js
└── views
    ├── index.js
    ├── loading.js
    ├── login.js
    ├── profile.js

views/index.js

[
  'loading',
  'login',
  'profile',
].forEach((file) => {
  exports[file] = require('./' + file);
});

but have instead got to do:

exports.loading = require('./loading');
exports.login = require('./login');
exports.profile = require('./profile');

I am doing this so that whenever I require('./views') i can reference any component without extra requires.

matejkramny avatar Nov 30 '15 11:11 matejkramny

@matejkramny No, React Native doesn't use NodeJS.

If you've worked with client side apps and bundling JavaScript with webpack or browserify, that's how it works. The JavaScript files need to be statically analyzed in order to be bundled. You cannot use dynamic strings.

satya164 avatar Nov 30 '15 11:11 satya164

I see, got a bit confused as its got node_modules, require and all that.

Thanks for explaining

matejkramny avatar Nov 30 '15 11:11 matejkramny

Hey guys, I'm trying to use the manual versions of this using source={{uri: "imagename"}} but it's not finding my files that in the same directory as the component rendering them.. How should my files be organized/ where should they be in order for this to work?

naji247 avatar Mar 31 '16 06:03 naji247

@naji247 You've to put the files under the res/drawable like you'd add images in Android.

satya164 avatar Mar 31 '16 07:03 satya164

@satya164 but how to statically analyzed? There's no res/drawable directort

nollydeng avatar Aug 31 '16 10:08 nollydeng

@nollydeng The folder drawable must be created under the already existing android/app/src/main/res. Add a file such as

android/app/src/main/res/drawable/myImage.png

and reference it in code as

<Image source={{uri: "myImage"}} />

aicioara avatar Dec 05 '16 03:12 aicioara

@aicioara But what about iOS?

dasmikko avatar Mar 03 '17 18:03 dasmikko

@dasmikko For iOS you need to include them as an asset, eg by placing them in your project much the same as you would a custom font or any other file. From that point on you can refer to the image by its exact filename (for iOS, including the extension, for Android, without).

Usage

So your image tag could be generically used as follows:

import { Platform, Image } from 'react-native

// ...

// render fn returns:
<Image source={{ uri: `filename${Platform.OS === 'ios' ? '.jpg' : ''}` }} />

For your convenience it might be worth making a quick wrapper around Image, call it something like ManuallyBundledImage (bad name, I know), and use that instead for the images you include manually.

Pixel density variants

iOS

iOS will automatically use @2x and @3x variants if you append that to their filenames. You do not need to change the uri in the image tag -- it should automatically grab the proper pixel density based on device:

// images to add to Xcode:
filename.jpg
[email protected]
[email protected]

Android

For android, you can use variants for pixel densities by placing ldpi, mdpi, hdpi, xhdpi, etc variants in the proper folders as follows:

android/app/src/main/res/drawable/filename.jpg // default fallback image
android/app/src/main/res/drawable-ldpi/filename.jpg // different resolution
... // other dpi variants
android/app/src/main/res/drawable-xxxhdpi/filename.jpg // different resolution

hilkeheremans avatar Mar 09 '17 07:03 hilkeheremans

Thats not really multiplatform solution. Is there any possible library or plugin which solves this for me?

obykoo avatar Mar 24 '17 15:03 obykoo

same problem. how could I concat my variable to the image path... Is there any other solution?

dalianmao22233 avatar Apr 26 '17 01:04 dalianmao22233

Same issue as above. If React Native is designed this way, then how do you handle a situation where you do an API call and render a local image based on what you get back?

RFSync avatar May 04 '17 00:05 RFSync

You must enumerate the local images, like

const IMAGES = {
  image1: require('../image1'), // statically analyzed
  image2: require('../image2'), // statically analyzed
}

getImage(num: number) { // dynamically invoked
  return IMAGES['image' + num];
}

sahrens avatar May 04 '17 00:05 sahrens

@sahrens, thanks! This worked perfectly for me.

In my component, I imported my equivalent of your IMAGES and used it in my Image element:

<Image source={IMAGES[image.key]} />

israelvicars avatar May 05 '17 02:05 israelvicars

@sahrens what if we have unknown number of images,, it can be 100 or 1000, we cant known the # of images at build time...

vvavepacket avatar May 06 '17 01:05 vvavepacket