0

How can I achieve this in react-native

require("../images/vehicles/" + this.state.proccessedFirstData.make + ".png")

make is the object property that I need to access dynamically, I have been searching around and I am not finding any solution

I also tried

const IMAGE = require("../images/vehicles/" + this.state.proccessedFirstData.make + ".png") and its not working

1
  • You cannot concat variables in require path. Actually you can but it is not recommended for as it can reduce the performance. Commented Apr 6, 2018 at 11:20

2 Answers 2

1

The RN bundler is static so you have to import all the resources at compile time.

You can still have a semi dynamic load:

const car1 = require('<path>') const car2 = require('<path>') const cars = {car1, car2} <image source={cars[this.state.car]}> 
Sign up to request clarification or add additional context in comments.

Comments

0

In JS require statements are resolved at bundle time (when the JS bundle is calculated). Therefore it's not supported to put variable expression as an argument for require.

In case of requiring resources it's even more trickier. When you have require('./someimage.png'), React Native packager will locale required image and it will be then bundled together with the app so that it can be used as a "static" resource when your app is running (in fact in dev mode it won't bundle the image with your app but instead the image will be served from the server, but this doesn't matter in your case).

If you want to use random image as a static resource you'd need to tell your app to bundle that image. You can do it in a few ways:

1) Add it as a static asset of your app, then reference to it with <Image src={{uri:'name_of_the_image_in_assets.png'}}/> (here is how you can add it to the native iOS app)

2) Require all the images upfront statically. Sth in a form of:

var randomImages = [ require('./image1.png'), require('./image2.png'), require('./image3.png'), ... ]; 

Then in your code you can do:

<Image src={randomImages[Math.floor(Math.random()*randomImages.length)]}/> 

3) Use network image with <Image src={{uri:'http://i.imgur.com/random.jpg'}}/>

ref from this link -- thanks @kzzzf

2 Comments

I get an error: require expect exactly 1 string literal argument
sorry it was not working @NtiyisoRikhotso i have updated my answer please check it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.