Nicasso Nicasso - 1 month ago 9
React JSX Question

Require a var that contains a var in react-native

I'm working with react native and I'm creating a Class for my Buttons. The button contains a image. Down here i've decelerated my button in my view.

var imageUrl = { //this is a var from a JSON object there could be more than 20 different images
normal: "../assets/images/emoticons/1.png",
selected: "../assets/images/emoticons/1-selected.png"
}

<Button key={index}
selected={true}
onPress={onSelect}
imageUrl={imageUrl} />


In the 'Button' Class I've created a _renderImage function that sets the image in the button.

_renderImage(imageUrl){
let image = (selected === true) ? require(imageUrl.normal) : require(imageUrl.selected); //get the right image url

console.log('../assets/images/emoticons/1.png'); //logs '../assets/images/emoticons/1.png'
console.log(typeof('../assets/images/emoticons/1.png')); //logs string
console.log(image); //logs '../assets/images/emoticons/1.png'
console.log(typeof(image)); //logs string

return (
<Image source={require(image)} />
);


}

This function gives a error. In the screenshot over here you can see the error.
Error screenshot in iOS simulator

When i manual set
<Image source= require('../assets/images/emoticons/1.png)} />
It renders the image. So the image exists on this location.

Similar Questions like this one doesn't fix my problem:
Trouble requiring image module in React Native

Answer

I do not think this is currently possible in React Native, as per docs:

Note that in order for this to work, the image name in require has to be known statically.

From https://facebook.github.io/react-native/docs/images.html