Michael L. Michael L. - 11 months ago 34
Javascript Question

How can you dynamically change the source in a require statement that requires an image file?

The image I'm using in React Native uses a require statement for the source of the image. I want to change the source of the image so it is kind of of like switching out frames in an animation.

var module1 = './hello';
var module2 = './goodbye';

state = {
module: module1 // will later be changed to module2



I ended up just creating an object like this:

var frames = { '1': require('./assets/phase1.png'), '2': require('./assets/phase2.png'), '3': require('./assets/phase3.png'), '4': require('./assets/phase4.png'), }

and in my Image tag, I set the source attribute to this.state.frame and setState with a new key from frames like frames[imageIndex]. Luckily I didn't have too many images, but this isn't the most ideal solution.

EDIT: Another solution (which is more elegant and less verbose) is to create a drawable folder in android>app>src>main>res and drop all the images in the that folder. On iOS, you can drop all your images in ios>Appname>Images.xcassets.

From there, you can set the source of your images to {uri: this.state.imageFile} where this.state.imageFile is a string without the file extension and you can change them dynamically without having to require() each file.