Reputation:
I am trying to create an app with react native, and want to have an image that can change depending on the circumstances. I want to have a list of paths, and then select the image by choosing an item in the list.
I have tried making an image that looks like this:
<Image source={require(icons[iconNum])} />
But whenever I try that, I get an error saying,
Requiring unkown module "./images/exampleImage.png".
I have also tried using a single variable, that isn't a list, and that gives me the same error. How could I use a variable to select the correct image that I want to use?
Upvotes: 2
Views: 296
Reputation: 22797
require
is a javascript keyword with a preload nature, you have to prepare every resources you want to use, simply create a resources file for that. ex:
export var icons = [
require('./icon/icon1.png'),
require('./icon/icon2.png'),
require('./icon/icon3.png'),
...
];
Images are pre-bundled into App, provide related path at runtime doesn't mean anything.
You can easily prove it by changing require("./icons/icon.png")
to require("./icons/"+"icon.png")
. Although they are logically the same, latter one will never works.
Upvotes: 3