i am making a language translation application, and i have the following code
var setInputLang = (item) => {
this.state.inputLang= item;
this.inputLangPic = //code here;
}
///This is called within a view in my render function
<TouchableOpacity //Code here to set country >
<Image
source = {require('../img/flags/png/india.png')}
style = {{flex: 0.33, height: 50, margin:10}}
/>
</TouchableOpacity>
Basically, i want to be able to, when the image is pressed, i want to set the input language's picture path to whatever the image is that is being pressed
I have multiple flags to choose from, and storing the inputLang would need to work for all of these. This is what i was planning on doing
this.inputLangPic = {require('../img/flags/' + inputLang + '.png')}
This does not work, i was wondering how to do this? The current code gives me an error saying "Unknown named module: '../img/flags/png/india.png', which is odd because i've used this before to generate the image and it works just fine
Thanks in advance
EDIT: also, how would i go about passing the variable into the inputLang from touchable opacity? I have marked where this is as "//Code here to set country"
ReactNative doesn't allow to dynamically load images. All the images(require statements) are parsed before and made sure they exists. In order to solve your problem you will have to populate your images first and then use them.
Here is one way you can do it
var imageMap = {
'uk.png' : require('../img/flags/uk.png'),
'india.png': require('../img/flags/india.png')
}
Then when you want to use the image do
<Image
source = {imageMap['india.png']}
style = {{flex: 0.33, height: 50, margin:10}}
/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With