By Shaheen Ghiassy


2015-06-15 20:16:26 8 Comments

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 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 native error with dynamic image name

7 comments

@Moso Akinyemi 2019-02-22 23:33:25

If you're looking for a way to create a list by looping through a JSON array of your images and descriptions for example, this will work for you.

  1. Create a file (to hold our JSON database) e.g ProfilesDB.js:

const Profiles=[
	  {
	  "id" : "1",
	  "name" : "Peter Parker",
	  "src" : require('../images/user1.png'),
	  "age":"70",
	},
	{
	"id" : "2",
	"name" : "Barack Obama",
	"src" : require('../images/user2.png'),
	"age":"19",
	},
	{
	"id" : "3",
	"name" : "Hilary Clinton",
	"src" : require('../images/user3.png'),
	"age":"50",
	}
]
export default Profiles;

  1. Then import the data in our component and loop through the list using a FlatList:

import Profiles from './ProfilesDB.js';

<FlatList	
 data={Profiles}
 keyExtractor={(item, index) => item.id}
 renderItem={({item}) => <View>
                            <Image source={item.src} />
                            <Text>{item.name}</Text>
                         </View>
   }
/>

Good luck!

@DaveClissold 2018-08-24 21:35:08

I know this is old but I'm going to add this here as I've found this question, whilst searching for a solution. The docs allow for a uri: 'Network Image'

https://facebook.github.io/react-native/docs/images#network-images

For me I got images working dynamically with this

<Image source={{uri: image}} />

@Walter Monecke 2017-07-31 14:22:31

RELEVANT IF YOU HAVE KNOWN IMAGES (URLS):

The way I hacked my way through this problem:

I created a file with an object that stored the image and the name of the image:

const images = {
  dog: {
    imgName: 'Dog', 
    uri: require('path/to/local/image')
  },
  cat: {
    imgName: 'Cat on a Boat', 
    uri: require('path/to/local/image')
  }
}

export { images };

Then I imported the object into the component where I want to use it and just do my conditional rendering like so:

import { images } from 'relative/path';

if (cond === 'cat') {
  let imgSource = images.cat.uri;
}

<Image source={imgSource} />

I know it is not the most efficient way but it is definitely a workaround.

Hope it helps!

@Tedy Kanjirathinkal 2017-09-01 16:28:10

Neat solution to handle a known set of images

@Walter Monecke 2017-09-01 17:01:30

@TedyKanjirathinkal I am glad it helped!

@Truca 2018-01-08 16:40:39

Thank you, this will be useful

@sabir 2019-02-19 02:28:48

@WalterMonecke: am getting integer value if we do like this

@Walter Monecke 2019-02-22 22:31:16

@sabir you mean the image is repsented by a number?

@BK7 2017-02-15 09:45:26

This worked for me :

I made a custom image component which takes in a boolean to check if the image is from web or is being passed from a local folder.

// In index.ios.js after importing the component
<CustomImage fromWeb={false} imageName={require('./images/logo.png')}/>

// In CustomImage.js which is my image component
<Image style={styles.image} source={this.props.imageName} />

If you see the code, instead of using one of these:

// NOTE: Neither of these will work
source={require('../images/'+imageName)} 
var imageName = require('../images/'+imageName)

Instead I'm just sending the entire require('./images/logo.png') as a prop. It works!

@dazziola 2017-02-23 23:56:29

This answer deserves more credit. It absolutely works when you declare the require statement and pass as a prop. Thank you so much for your simple explanation, I only wish others would be as clear.

@BK7 2017-02-24 15:05:34

Thanks @dazziola

@dasmikko 2017-03-03 19:25:44

The prop thing work wonders. That should be stated on the official docs.

@Pablo 2017-07-17 14:50:11

It didn't work for me.

@BK7 2017-07-17 14:51:20

@Pablo show your code here please

@Pablo 2017-07-17 14:55:00

class CustomImage extends Component { constructor(props) { super(props); } render() { return ( <Image source={this.props.imageName} resizeMode="contain" style={{ height: 24, width: 24 }} /> ); } } <CustomImage fromWeb={false} imageName={require(`../../images/phone-${item.status}.png`)} />

@BK7 2017-07-17 21:15:33

Looks right.. what is the error?

@Walter Monecke 2017-07-29 13:14:25

I did not work for me either

@Walter Monecke 2017-07-29 13:16:41

In the parent Component I have <CustomImage fromWeb={false} imageName={require(../../assets/icons/${el.img}.png)} /> and this in the child component class CustomImage extends Component { constructor(props) { super(props); } render() { return ( <Image source={this.props.imageName} resizeMode="contain" style={{ height: 24, width: 24 }} /> ); } }

@Walter Monecke 2017-07-29 13:18:53

Do I still have to add the images to xCode?

@Walter Monecke 2017-07-29 13:27:56

@BK7 It seems that i works for you because you hardcoded the URL in the CustomImage tag. However, mine is dynamic.

@BK7 2017-07-31 12:27:00

@WalterMonecke I think you're right, I just checked for dynamic URLs, it's not working. You need not add images separately to Xcode as react-native link will take care of it.

@armnotstrong 2017-08-23 03:23:16

Hi, dear @BK7 I tried your answer and it didn't work check this, what did I missing? could you help with a check? have been stuck here :D

@BK7 2017-08-23 08:53:41

Hi @armnotstrong, It doesn't work because you're passing a variable to the require method, i.e require(item). unfortunately, it works only if you pass hardcoded urls i.e the string as quoted in the above example. Still couldn't figure out why that happens. I'd recommend you upload these files in AWS S3 or firebase hosting etc.. and use the uri method of getting images instead.

@armnotstrong 2017-08-23 09:30:26

@BK7 thanks for replying that, and I have chosen to input all those file paths with my bare hand, this is insane and hope reactnative could fix that :-(

@BK7 2017-08-23 11:08:33

@armnotstrong Hopefully.

@Sumit Sahoo 2019-01-20 16:06:46

Pure genius, this is exactly what I was searching for :)

@SamYang 2015-12-28 02:14:39

you can use

<Image source={{uri: 'imagename'}} style={{width: 40, height: 40}} />

to show image.

from:

https://facebook.github.io/react-native/docs/images.html#images-from-hybrid-app-s-resources

@Colin Ramsay 2015-06-16 12:50:33

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

@coderzzz18 2016-12-19 09:51:53

where should I add images , i am using react native for android,in the drawable folder?

@app_sciences 2017-01-15 23:19:29

The link above is incorrect, the article is now at facebook.github.io/react-native/docs/images.html

@chanjianyi 2017-01-26 07:17:10

hi , how to do if I have hundreds of images need to require?

@Mo. 2018-05-11 00:26:18

@chanjianyi I am on the same situation :-(

@Richard Kho 2015-06-16 03:54:20

You should use an object for that.

For example, let's say that I've made an AJAX request to an API and it returns an image link that I'll save to state as imageLink:

source={{uri: this.state.imageLink}}

@Robert Tomas G IV 2016-05-27 18:07:08

for dynamic image path links, this doesn't work: var img = "../img/icons/"+img_name+"_selected.png"; <br/> <Image source={{uri: img}} resizeMode={'contain'} />

@Gabriel Lupu 2016-11-27 19:02:35

a hack for this, if you know all the img_name variants would be to go this way: var images = { 'first': require('../first.png'), 'second': require('../second.png') } <Image source={{uri:images[img_name]}} resizeMode={'contain'} />

@Lashae 2017-04-13 10:38:57

Please be warned that for @GabrielLupu 's suggestion: You are allocating all of the images in the memory by this way. It depends on the number of images and their sizes however you will likely experience out of memory errors.

Related Questions

Sponsored Content

23 Answered Questions

[SOLVED] What is the difference between React Native and React?

9 Answered Questions

[SOLVED] When should I use curly braces for ES6 import?

5 Answered Questions

[SOLVED] React Native: require() with Dynamic String?

7 Answered Questions

[SOLVED] Trouble requiring image module in React Native

1 Answered Questions

1 Answered Questions

[SOLVED] react native require not working for image source

  • 2016-12-08 07:09:39
  • suman j
  • 2312 View
  • 2 Score
  • 1 Answer
  • Tags:   react-native

3 Answered Questions

[SOLVED] React Native images with dynamic names

0 Answered Questions

1 Answered Questions

[SOLVED] requiring image in react-native 0.14.2

  • 2015-11-30 12:51:40
  • Aakash Sigdel
  • 929 View
  • 7 Score
  • 1 Answer
  • Tags:   react-native

1 Answered Questions

[SOLVED] Resource ID #0x0 React Native

  • 2015-09-17 16:40:14
  • maraujop
  • 814 View
  • 3 Score
  • 1 Answer
  • Tags:   react-native

Sponsored Content