Constructing the path to the local resource - javascript

During the tests, I constructed a wall for pictures that was then used in the list of objects
const przyklad = require('../assets/servicesIcons/przyklad.png');
const product =
[
{
id: 1,
image: przyklad,
title: 'przyklad'
},
{
id: 2,
image: przykald2,
title: 'przyklad2
},
In Flatlista I downloaded objects and saw a list of pictures with the title. At the moment I wanted to change so that everything was downlad from the DB but the does not get me a picture, I do not know how to connect this string from the DB with require to read the picture?
function Product({id, image , title}) {
const navigation = useNavigation();
return (
<View style={styles.rootCointener}>
<TouchableOpacity onPress={() => {navigation.replace('Term', {id: id, title: title})}}>
<Image style={styles.imageCointener} source={image} />
</TouchableOpacity>
<Text style={styles.textCointener}>{title}</Text>
</View>
)
}

If you are getting Base64 string from your DB for the image. You can use it as following
const base64Image = 'data:image/png;base64, <Your Base64 string>'
<Image style={styles.imageCointener} source={{uri: base64Image}}/>
Note: Please comment / edit the quetion with what is the response ur getting from the DB So that I can assist better.

Related

How to append the value of a variable in a Image uri | React Native

const Stories = ({
id,
profileImg,
text,
}) => {
return (
<View>
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
<Image
// source={{ uri: {profileImg}}
/>
</ScrollView>
</View>
)
}
I am trying to use the value of a variable as a URI in react Native but its not working. I had tried putting the value of that parameter in {} like {profileImg} but it failed and the image is not rendering on the page
You can do something like
const baseUrl = 'https://whatever.com'
const valueToBeAdded = "userProfile";
const profileImg = `${baseUrl}/${valueToBeAdded}`
source={{ uri: {profileImg}}
this should work

trying to pass data between screens but getting the TypeError: undefined is not an object (evaluating 'route.params.item')

so here I have a home screen and trying to title, rating and body to the reviews screen it used to work when I used const { item } = route.params; but now I get the TypeError: undefined is not an object (evaluating 'route.params.item') error and couldn't find any solution or understand why.
const HomeScreen = ({ navigation }) => {
const [reviews, setReviews] = useState([
{ title: 'Zelda, Breath of Fresh Air', rating: 5, body: 'lorem ipsum', key: '1' },
{ title: 'Gotta Catch Them All (again)', rating: 4, body: 'lorem ipsum', key: '2' },
{ title: 'Not So "Final" Fantasy', rating: 3, body: 'lorem ipsum', key: '3' },
]);
return (
<View style={styles.home}>
<StatusBar style="auto" />
<FlatList
data={reviews}
renderItem={({ item }) => (
<TouchableOpacity onPress={() => navigation.navigate('Reviews', { item })}>
<Text style={styles.homeText}>{item.title}</Text>
</TouchableOpacity>
)}
/>
</View>
)
};
const ReviewsScreen = ({ navigation, route}) => {
const { item } = route.params;
return (
<View style={styles.container}>
<StatusBar style="auto" />
<Text style={styles.homeText}>{item.title}</Text>
<Text style={styles.homeText}>{item.body}</Text>
<Text style={styles.homeText}>{item.rating}</Text>
<View style={styles.button}>
<Button title='home' color={'coral'} onPress={() => navigation.goBack()}/>
</View>
</View>
);
};
< HomeScreen navigation={navigation} route={route}/> brings the home screen to reviews but I only want the title, body and rating. I don't think this is the correct way to handle this problem.
The error speaks for it self.
In order to debug it, you first need to log route in ReviewsScreen.
Try this:
console.log(route)
And see, if there is item available in its properties?
This is how you should be debugging your problems.
My best shot without seeing the logs at all is that you are incorrectly sending params to the child screen.
Maybe you should try this?
navigation.navigate('Reviews', item)
Your are getting
TypeError: undefined is not an object (evaluating'route.params.item')
error because you are not assigning any value to item and the next screen is getting undefined value so you have to assign value just like this
navigation.navigate('Reviews',{item:item})
For more details you can check official
React Navigation docs
found the problem, instead of sending the data to the screen I was sending it to the stack component...

Why are other images from media library displaying in react native / expo project?

My fairly basic react native project uses expo-media-library to retrieve some photographs from a users photo album, presenting them in a stack of cards - kinda similar to Tinder. My code generally works, however instead of just displaying the top photo/card, several others are displayed in the first few seconds and I can't figure out why. I think it has to do with the size of the images and the delay in loading them but I'm not sure. I'd really appreciate advice about how to fix this.
Here's what's happening:
As you can see, instead of displaying the first image on the stack, another image is displayed briefly first even though I have not coded for this to happen.
Here is my code (leaving out imports and styles):
const ImageStack = ({navigation, route}) => {
const [status, requestPermission] = MediaLibrary.usePermissions()
const [photos, setPhotos] = useState([]) //where we store stack of cards
const [isLoading, setIsLoading]=useState(true) //only displaying stack when images have loaded
// On load, retrieve photos from gallery
useEffect(async()=>{
const getPhotos = await getAllPhotos(route.params.id)//id for the album is passed to component
setPhotos(getPhotos)
setIsLoading(false) // only when photos have been retrieved should they be displayed
},[])
// function to retrieve photos from gallery
const getAllPhotos = async (id) => {
let album = await MediaLibrary.getAssetsAsync({album: id, mediaType: 'photo', first: 20, sortBy: ['creationTime']})
const foundPhotos = album['assets']
const updatedPhotos = []
for (let i=0;i<foundPhotos.length;i++){
const updatedPhoto = await MediaLibrary.getAssetInfoAsync(foundPhotos[i].id)
updatedPhotos.push({
uri: updatedPhoto['localUri'],
id: updatedPhoto['id']
})
}
return updatedPhotos
}
const renderCards = () => {
return photos.map((item, i)=>{
return(
<Animated.View key={item.id} style={{height: SCREEN_HEIGHT -120, width: SCREEN_WIDTH, padding: 10, position: 'absolute'}}>
<Image source={{uri: item.uri}} style={{flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 20}}/>
</Animated.View>
)
})
}
return (
<View style={{flex:1}}>
<View style={{height:60}}>
</View>
<View style={{flex:1}}>
{!isLoading && renderCards()} //Only render the photo cards when loaded
</View>
<View style={{height:60}}>
</View>
</View>
Any suggestion how to fix this? Thanks!
Fixed this. So the issue was the size of the images. I added image compression which completely fixed the problem:
const compressedImage = await ImageManipulator.manipulateAsync(updatedPhoto.localUri, [], { compress: 0.2 });

the library "react-native-snap-carousel" is not processing the card image

I am new in react native and I was trying to use the "react-native-snap-carousel". The carousel is working with the parameters in the "carouselItems" variable as I sent, but the image is not working. I supoused to place it at the Card as a background image, with a short description with the same parameter array, but it is not working.
Can anyone help me to set it?
the array used to fill the cards:
const carouselItems = [
{
title: "Doce",
text: "[TEXTO DESCRITIVO]",
thumbnail: "assets/splash.png",
},
{
title: "Salgado",
text: "[DESCRIÇÃO]",
thumbnail: "assets/splash.png",
},
]
the folder structure is:
homemade-app / assets / splash.png
return (
<View style={styles.item}>
<ParallaxImage
source={{ uri: item.thumbnail }}
containerStyle={styles.imageContainer}
style={styles.image}
parallaxFactor={0.2}
{...parallaxProps}
/>
{item.thumbnail}
<Text style={styles.title} numberOfLines={2}>
{item.title}
</Text>
</View>
)
}
const goForward = () => {
carouselRef.current.snapToNext();
};
return (
<View style={styles.container}>
<TouchableOpacity onPress={goForward}>
<Text>go to next slide</Text>
</TouchableOpacity>
<Carousel
layout={"default"}
ref={ref => carousel = ref}
data={carouselItems}
sliderWidth={screenWidth}
sliderHeight={screenWidth}
itemWidth={screenWidth - 60}
renderItem={renderItem}
onSnapToItem={index => setState({ activeIndex: index })}
hasParallaxImages={true} />
</View>
);
}
I saw the article about how to handle local file with assets, but I still could not make it work properly.
Link to the article: (https://dev.to/fdefreitas/how-to-obtain-a-uri-for-an-image-asset-in-react-native-with-expo-7bm)
If you are using expo. First of all try with a static route remember you need full path not assets/myimage this is wrong, because sometime use it from array give problems like in this question Render images sources from parsed array of objects in react native .
array
const carouselItems = [
{
title: "Doce",
text: "[TEXTO DESCRITIVO]",
thumbnail: require("./../assets/splash.png"),
},
{
title: "Salgado",
text: "[DESCRIÇÃO]",
thumbnail: require("./../assets/splash.png"),
},
]
<ParallaxImage
source={require('#expo/snack-static/yourimage.png')}
...
/>
or put your image in same folder
<ParallaxImage
source={require('./your-image.png')}
...
/>

Setting source of <Image/> with variable

I am trying some react native code which is as follows , I want to set the static images to an image view as follows but it doesn't load
const items = [
{ name: './images/home.png', code: '#1abc9c' }, { name: './images/home.png', code: '#2ecc71' },
{ name: './images/home.png', code: '#3498db' }, { name: './images/home.png', code: '#9b59b6' }
];
return (
<ImageBackground
source={require('./images/marble.jpg')}
style={styles.backgroundImage}>
<GridView
itemDimension={130}
items={items}
style={styles.gridView}
renderItem={item => (
<View style={[styles.itemContainer, { backgroundColor: item.code }]}>
<Image source={require(item.name)}></Image>
</View>
)}
/>
</ImageBackground>
);
Error I get is
calls to require expect exactly 1 string literal argument, but this was found: require(item.name).
Ofcourse I am new to react native so kindly ignore my missed terminology
You try like this
const items = [{ name: require('./images/home.png'), code: '#1abc9c' },{...}]
then
<Image source={item.name}></Image>

Categories