React Native: How to import local image with dynamic name - android

I have about 100 heroes' image on local that need to import into the listview. This is my hero.js
renderRow(hero) {
return (
<View>
<View style={styles.container}>
<Image
source={require('./img/hero/'+hero.img+'.jpg')}
style={styles.thumbnail} />
<View style={styles.rightContainer}>
<Text style={styles.title}>{hero.name}</Text>
</View>
</View>
<View style={styles.separator} />
</View>
);
After some research I know require won't allow dynamic name. I also tried uri, no error but no image either.
{{uri: './img/hero/'+hero.img+'.jpg'}}
My folder structure is like this:
Project
index.ios.js
hero.js
img
hero
What is the best way to handle this, I don't want to put images on the network.

sahrens said the following on this forum
We intentionally don't support dynamically generated image names because it makes it very hard to manage assets over time, just like how you wouldn't want to do
It looks like it can be done via uri but it will require a bit of work. You will need to add your images in xcode assets and for android under res/drawable.
Then you can get your image with <Image source={{ uri: "image" + "name" }} />

I solved this issue in one way, just post my answer here in case others interesting on how to deal with this.
I wrote a php script to read all images in my hero folder and print out in this format:
heroName: require ('./img/hero/heroName.jpg')
<?php
$dir = "./img/hero";
// Open a known directory, and proceed to read its contents
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
$images = array();
while (($file = readdir($dh)) !== false) {
$keyName = str_replace(".jpg","",$file);
print "$keyName: require('./img/hero/$file'),". "<br />";
}
closedir($dh);
}
}
?>
Then I copy the result, paste into a js file and store as object like this:
export default heroList = {
name1: require('./img/hero/name1.jpg'),
name2: require('./img/hero/name2.jpg'),
etc....
}
Finally in my hero.js file:
import heroList from './heroList';
....
source={heroList[heroName]}

Related

React Native: Images from uri not being rendered on Android using String interpolation to hand over token

I am currently working on a React Native App that involves images. I use the following code to display them:
//...
<View key={uriFromArray}>
<Image
style={styles.itemimage}
source={
{
uri: uriFromArray,
headers: {
Authorization: `Bearer ${graphToken}`,
},
}
}
/>
</View>
//...
On iOS, this works totally fine, on Android though, the images are not being rendered, neither on a virtual nor a physical device. Weirdly enough, images are being rendered if I copy the acutal token string to Authorization instead of using String interpolation to hand over the token.
Does anybody have an idea of what could be wrong? Thanks!
Try concatenating string before the component renders like:
const header = `Bearer ${graphToken}`;
Then pass it to Authorization key in the Image uri header prop

Dynamically set uri of a react native <Image />

I am trying to build a FlatList which will have an icon on the left (pretty much like any Contacts app) and I'm trying to dynamically load an image based on the name of the element
<Image
style={styles.image}
source={{uri: `./assets/${this.props.name}.png`}}
/>
Which is not allowed by React Native, as stated by their Image docs.
Are there any workaround?
if your image is in your project (eg assets folder) you can not create dynamically, the most you can do is an array to select, like this:
var icons = [ require('image!my-icon-active') ,require('image!my-icon-inactive')];
<Image
style={styles.image}
source={icons[1]}
/>
but you can save the images in a folder and read from your local storage using 'file://' or 'data://' like you are reading from Web, that can be dinamically link:
let uri = 'file://'+this.state.pathToResources+'/'+href;
<Image
style={{width: 400, height: 400}}
resizeMode='contain'
source={{uri}}
/>
You can use the lib
https://github.com/itinance/react-native-fs
for you ready from local disk of your smartphone, but you need manage the height e width.
For more read https://facebook.github.io/react-native/docs/images.html#uri-data-images
Just create a variable in the state:
constructor(props) {
super(props);
this.state = {
imgUri: ""
}
}
...
<Image
style={styles.image}
source={{uri: this.state.uri}}/>
Update the uri by calling this.setState({imgUri: "foobar"})

Convert from image to url in react native

may I know how to change the image to the URL or link in react native? Below are the screenshot and the code:
The image can display at here but I want to make it become a link in attachment field here
Example of the URL or link: "http://exampleimage.jpg"
Here is the code
<TextInput
onChangeText={(attachment) => {
this.setState({attachment})
}}
placeholder="Attachment"
style={styles.input}
/>
{img}
<TouchableOpacity onPress={this.show.bind(this)}>
<Icon name="device-camera" size={20} color="black"/>
</TouchableOpacity>
...
show(){
pick((source, data) => this.setState({avatarSource: source, data: data}));}
I use the react-native-image-picker to do it. Please advise on how to do it. Any help will be appreciated. Thank you.
Create let variable in render block with.
Assign Image Url to let variable using uri .
Add Image tag in render’s return block.
Add Source attribute in Image tag and Assign Let variable name to it.
Add inline style to Image tag.

React Native Image uri doesn't work

I tried to display an image from a local file, so I try to do this
<Image
source={{uri:'../../assets/img_src/BTI.jpg'}}
style={{height:150,width:150}}
/>
my container component seems getting the height and the width but the image doesn't load. So I try this
<Image
source={require('../../assets/img_src/BTI.jpg')}
style={{height:150,width:150}}
/>
It works really well, unfortunately as far as I know I can't use this implementation if i want to manipulate the address file first and store it to a variable.
Example:
const imgSrc = `../../assets/${data.image}`;
where the data.image = 'img_src/BTI.jpg'.
I try to delete all the data on my android simulator in the android studio but the result is still the same. Am I doing something wrong? Is there a better implementation for this?
Thanks a lot :)
Not being able to require() a dynamic path is an intended behaviour of React Native, the packager needs to know paths in advance - see React Native issues
We had this problem in our project, we were storing image URLs on our DB and wanted to concat strings in the app to get the path to the locally stored image. As you've discovered, this doesn't work. You might find our workaround useful.
In our /images folder, we created a new images.js file which simply exported an object whose keys mapped to all our local image paths like so
export const Images = {
image1: require('./image1.png'),
image2: require('./image2.png'),
image3: require('./image3.png'),
};
Now the packager knew all the paths in advance and was happy. Then we added an imageKey to the DB item and used this rather than the absolute path. To grab an image we simply did
import { Images } from '../images/images';
// get your image key e.g. passed down through props
const img = Images[imageKey];
...
render() {
...
<Image source={img} />
...
}
Might not fit your exact use case, but hopefully you might be able to make some use of it.

Save image from URL to device with React Native

Hi as title suggests I need to save images to Android device from my CDN.
I am building app with React Native, and what I've done is that:
fetch('https://server.com/images.json').then((json) => console.log(json))
Which returns json:
{images: ["cdn.server.com/image1.jpg", "cdn.server.com/image2.jpg"]}
And now I really don't know what to do to save images to my device, because then I need to use them to open Instagram Intent (https://www.instagram.com/developer/mobile-sharing/android-intents/) and it only works if image is saved to device.
Any ideas?
I don't know react can using Java code.
I offen using this code to get image from url.
String imageCDN = json.getString("images");
ImageLoader imageLoader = new ImageLoader(this);
ImageView imgflag = (ImageView) findViewById(R.id.flag);
imageLoader.DisplayImage(imageCDN, imgflag);
But you should read this tutorial
At this code:
renderMovie(movie) {
return (
<View style={styles.container}>
<Image
source={{uri: movie.posters.thumbnail}}
style={styles.thumbnail}
/>
<View style={styles.rightContainer}>
<Text style={styles.title}>{movie.title}</Text>
<Text style={styles.year}>{movie.year}</Text>
</View>
</View>
);
}
You don't need to save image because memory leak, using ListView to clone all image in DataSource.

Categories

Resources