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
Answer from Colin Ramsay on Stack OverflowThis 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
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:
export const ANIMAL_IMAGES = {
dog: {
imgName: 'Dog',
uri: require('path/to/local/image')
},
cat: {
imgName: 'Cat on a Boat',
uri: require('path/to/local/image')
}
}
Then I imported the object into the component where I want to use it and just do my conditional rendering like so:
import { ANIMAL_IMAGES } from 'path/to/images/object';
let imgSource = null;
if (condition === 'cat') {
imgSource = ANIMAL_IMAGES.cat.uri;
}
<Image source={imgSource} />
I know it is not the most efficient way but it is definitely a workaround.
Hope it helps!
React Native: require() with Dynamic String?
How to use require with a path passed from a different file for an image?
Dynamic import path for React Native - javascript
React Native: how to use require(path) with dynamic urls?
Videos
React's require() only uses static url not variables, that means that you have to do require('/path/file'), take a look at this issue on github and this one for more alternative solutions, there are a couple of other ways to do it!
for e.g
const images = {
profile: {
profile: require('./profile/profile.png'),
comments: require('./profile/comments.png'),
},
image1: require('./image1.jpg'),
image2: require('./image2.jpg'),
};
export default images;
then
import Images from './img/index';
render() {
<Image source={Images.profile.comments} />
}
from this answer
Here is my solution.
Setup
File structure:
app
|--src
|--assets
|--images
|--logos
|--small_kl_logo.png
|--small_a1_logo.png
|--small_kc_logo.png
|--small_nv_logo.png
|--small_other_logo.png
|--index.js
|--SearchableList.js
In index.js, I have this:
const images = {
logos: {
kl: require('./logos/small_kl_logo.png'),
a1: require('./logos/small_a1_logo.png'),
kc: require('./logos/small_kc_logo.png'),
nv: require('./logos/small_nv_logo.png'),
other: require('./logos/small_other_logo.png'),
}
};
export default images;
In my SearchableList.js component, I then imported the Images component like this:
import Images from './assets/images';
I then created a new function imageSelect in my component:
imageSelect = network => {
if (network === null) {
return Images.logos.other;
}
const networkArray = {
'KL': Images.logos.kl,
'A1': Images.logos.a1,
'KC': Images.logos.kc,
'NV': Images.logos.nv,
'Other': Images.logos.other,
};
return networkArray[network];
};
Then in my components render function I call this new imageSelect function to dynamically assign the desired Image based on the value in the this.state.network:
render() {
<Image source={this.imageSelect(this.state.network)} />
}
The value passed into the imageSelect function could be any dynamic string. I just chose to have it set in the state first and then passed in.
I hope this answer helps. :)
I have an image path in a different file as a string, which I want to pass to another component and then pass into the source of an image.
So basically I want to get path information like from imagePath1 from a different file.
const imagePath1 = '../assets/metaformTools_colorful_choices_big_web.jpg';const imagePath2 = value.picture;
When I console.log imagePath1 and imagePath2 are the same (true):
console.log(imagePath === imagePath2)
Here only imagePath1 works, although they should be the same
Works:
<ImageBackground style={styles.imageBackground} source={require('imagePath1')} />
Does not work:
<ImageBackground style={styles.imageBackground} source={require('imagePath2')} />
I saw that a lot of people have this problem when googling, unfortunately I did not find a solution which worked and did not really understand the problem.
Would be happy if someone could help! (bear with me, I am a beginner)
From Marc Shilling's answer on https://github.com/facebook/react-native/issues/3099
You can use an absolute path on imports/requires:
import {ProximaNovaText} from 'MyApp/src/components'; require('MyApp/src/utils/moment-twitter');where 'MyApp' is whatever name you registered in your index.ios.js file
Note for VS Code: This works, but be warned that you might lose intellisense and cmd/ctrl + click. Thanks Johan for the info about CS code
You can mark a directory as a package by adding a package.json within the root directory you want to resolve.
e.g:
- app
- package.json // โ Add this package.json file
- config
- components
- ... (etc)
package.json should look like this:
{ "name": "app" }
Restart your packager
react-native start --reset-cache
Now you can use the following in all of you project files:
import store from 'app/config/store';
import Button from 'app/components/Button';
You can use this same method across other directories in your project, I don't think this works via require, although image paths seemed work.
As noted in the comments, you may lose auto-complete in your editor (VSCode).
For Jetbrains IDE's there are some ongoing tickets here:
- https://youtrack.jetbrains.com/issue/WEB-17254
- https://youtrack.jetbrains.com/issue/WEB-20104#comment=27-1486526
- https://intellij-support.jetbrains.com/hc/en-us/community/posts/205434510-Configure-custom-modules-resolve-folder
This might help with Jetbrains IDE's in the meantime.
// A slash may allow auto-complete to work in your IDE (but will fail to resolve)
import Button from '/app/components/Button'; // Cannot be resolved
Dynamic paths in require are not currently supported. Please check this 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('name-of-the-asset') in the source.
You can use a switch statement to implement this.
I'm not sure about it but you can try to write it in ES6
require(`index/components/${name}`);
Hi everybody, I'm trying to show a randomly generated image in my Image component, however I'm getting the following error:
invalid call at line 58:require(getRandomImage())
My component:
const [ randomImages, setRandomImages ] = useState([
//require('../assets/images/aranda.jpg'),
require('@assets/images/bilmore.jpg'),
require('@assets/images/cachalote.jpg'),
require('@assets/images/lola.jpg'),
require('@assets/images/meson.jpg'),
require('@assets/images/paloma.jpg'),
require('@assets/images/picasso.jpg'),
require('@assets/images/pimpi.jpg'),
require('@assets/images/tintero.jpg'),
require('@assets/images/tropicana.jpg'),
]);
const getRandomImage = () =>
{
return randomImages[rand(0,9)];
};
const rand = (min, max) =>
{
return Math.floor(Math.random() * (max - min)) + min;
}
<Image style={{ width:'100%', height:200,}} resizeMode="cover" source={require(getRandomImage())}/>