2

I have an array of 150 buttons that link to 150 pictures, i need to show the picture once the button is pressed. The information for the buttons is stored in a JSON file. The pictures names are the ID's of the buttons, so 1.jpg, 2.jpg etc.

Now I am facing the problem that I can't write:

 fish["image"] = {uri: "asset-library://" + fish.id + ".jpg"}; 

And the other solution with if statements does not work since I have so many options, any ideas?

Thanks so much

2 Answers 2

3

I had a similar problem. I built a function that contains a huge switch statement and has static requires for every case.

function getImage(id) { switch(id) { case 1: return require('./img/1.jpg'); case 2: return require('./img/2.jpg'); ... } } 

Now you can do

fish["image"] = getImage(fish.id); 

I also had to use over 100 icons, so instead of writing the cases by hand, I built a script that generates the function automatically.

Sign up to request clarification or add additional context in comments.

2 Comments

This is my sad fallback plan, but I am really hoping someone can come up with something better
@AdamKatz I don't think someone will. The way React Native solves the local image problem is by inlining the result of the require on compile time. Every string concatenation does not allow one to do such a thing.
3

I had too this problem for a component I developed. I used base64 image in json file. But maybe it's not a good fit for you, I hope it can help.

<Image style={styles.imgStyle} source={{uri: CountryFlags[country.cca2]}} /> 

You can see it here : https://github.com/xcarpentier/react-native-country-picker-modal/blob/master/src/index.js#L137-L139

And if you have a folder with files on it, simply convert images like that :

#!/bin/sh list=`ls ./flags | grep '[A-Z]'` echo "{" for item in $list do header="data:image/png;base64," img64=`ls ./flags/$item | xargs cat | base64` echo ${item:0:2} :\'$header$img64\', done echo "}" 

6 Comments

I'm trying to understand this solution. What's a cca2 Is that just an integer index value? Is that an undeclared variable and file suffix of your own design?
@zipzit country.cca2 is the ISO code of the countries, like US or FR and correspond to a key in the CountryFlag.js file containing a json with country correspondant to its flag encode into base64.
@DanielSchmidt : Thanks !
Thx. And +1 for sharing that code to convert over the image files!
Thanks for this, it is a good idea unfortuanately it doesn't help for my particualr situation as I don't have control over the JSON file as it is served over a web servcice that I have no control over, still going to up vote you.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.