Fetch data and add to variable - android

Hello I'm working with my project and I want to fetch poster_patch into variable to print every single image of miniatures in my app. Im working with react-native in. Here is some code of my app. I want to create function to fetch value of path_poster and add it after to uri
Top.js
`
import React,{useState,useEffect} from "react";
import { View, StyleSheet, Text } from "react-native";
import MovieBox from './MovieBox';
const API_URL="https://api.themoviedb.org/3/movie/top_rated?api_key=xxx"
export default function Top(){
const [movies,setMovies]=useState([]);
useEffect(()=>{
fetch(API_URL)
.then((res)=>res.json())
.then(data =>{
console.log(data);
setMovies(data.results);
})
}, [])
return (
movies.map((movieReq)=><MovieBox key ={movieReq.id} {...movieReq}/>)
);
};
`
MovieBox.js
`
import React from 'react';
import { View, StyleSheet, Text,Image } from "react-native";
const API_IMG = "https://image.tmdb.org/t/p/w500";
function MovieBox ({title, poster_patch,vote_average,release_date,overview}){
const styles = StyleSheet.create({
container: {
paddingTop: 50,
},
tinyLogo: {
width: 50,
height: 50,
},
logo: {
width: 66,
height: 58,
},
});
return(
<View>
<Text>
{title} rated:
{vote_average}
</Text>
<Image source={{
uri: API_IMG + HERE I WANT TO ADD VARIABLE TO POSTER_PATCH,
}}
style={styles.tinyLogo}
/>
</View>
)
}
export default MovieBox;
`
How to get values from poster_path and add it into uri

Join base url and path for example using concat.
<Image source={{
uri: API_IMG.concat(poster_path),
}}
style={styles.tinyLogo}
/>
See Images for details.

Related

React Native The View Doesnt Work On If Statment

onValueChange={(itemValue) => {
setSelectedValue(itemValue);
if(itemValue == 'other'){
alert('You Choose: '+itemValue+' Nice')
return(
// The <View> Doesnt Work Why ????
<View style={{backgroundColor:'red',height:5000,width:5000,}}>
<Text>Anas</Text>
</View>
)
}
}}
The Doesnt Work Why ????
i cant put it in if statment or i can ?
i dont hava idea !!
I put together a small sandbox where you can see an example of how to achieve what you want: https://codesandbox.io/s/sad-bird-lzzbb
import React, { useState } from "react";
import { Button, Text, View } from "react-native";
export default function App() {
const [selectValue, setSelectedValue] = useState('');
const onValueChange = (itemValue) => {
setSelectedValue(itemValue);
};
return (
<div className="App">
<Button
onPress={() => onValueChange("other")}
title="Click to set value to 'other'"
/>
{selectValue === "other" ? (
<View style={{ backgroundColor: "red", height: 5000, width: 5000 }}>
<Text>Anas</Text>
</View>
) : null}
</div>
);
}
You can use the onValueChange function to pass it as callback in any event you want (like the onPress of that button I have created) but then you need to return all jsx in the return of your functional component (or the render function if you're using class components)

Custom splash screen adding mp4 video(?)

I trying to add a video for my splash screen in my react-native app I added some lines of code and get no errors but the splash screen video doesn't play when starting the app by clicking the icon on an android phone or emulator. I created a folder where the video is. Any feedback is appreciated :)
import React, {useEffect} from 'react'
import {StyleSheet, View, Video, Text, Image} from 'react-native'
import Color from '../utils/Colors'
import Images from '../const/Images'
import Constants from '../const/Constants'
import firebase from '../firebase/Firebase'
import Video from '../video/Video'
function SplashScreen({navigation}){
useEffect(()=> {
NavigateToAuthORGroupScreen()
}, [navigation])
function NavigateToAuthORGroupScreen(){
setTimeout(function (){
firebase.auth().onAuthStateChanged((user) => {
if (user != null){
navigation.reset({
index:0,
routes: [{name: 'Groups Screen'}]
})
}else{
navigation.reset({
index:0,
routes: [{name: 'SignInScreen'}]
})
}
})
},2600)
}
return(
<View style = {styles.constainer}>
<Image style = {styles.logo} source = {Images.logo}></Image>
<Video style = {styles.video} source = {Images.video} autoPlay loop></Video>
</View>
)
}
const styles = StyleSheet.create({
video:{
width: '100%',
height: 0.06 * Constants.screenHeight
},
logo: {
alignSelf: 'center',
margin: 0.04 * Constants.screenHeight
},
constainer: {
flex: 1,
justifyContent: 'center',
alignItems:'center',
backgroundColor: Color.vibenote
}
})
export default SplashScreen
Images.js file: below
const images = {
logo: require('../../assets/logo.png'),
add: require('../../assets/add.png'),
logout: require('../../assets/logout.png'),
groups: require('../../assets/groups.png'),
video: require('../../assets/vnspl.mp4')
Can You Please Show the error that you get?
One more thing you called VideoView but I can't see you import any VideoView in your code.

React native maps showsMyLocationButton position

I am using Expo react-native-app. I have some local data which I want show in maps. For maps I have used React-native-maps. I successfully pull the data and display in maps by using Marker. For user location I have used expo-location and expo-permission. That works fine. I have used React-native-maps one props called showsMyLocationButton, by default props boolean false. when I made it true I can able to see in IOS Emulator and i think by default position bottom-right. Android emulator I don't see the button at all. This is ios image and this android image. I want to display some data under the maps like a Bottom-Sheet, for that I have used this package. As a result it hide the ios' showsMyLocationButton.
I want to display the user current location Button like Uber. I tried lots of way to do that but could not able to achieve the goal. I want change the button icon as well but also failed. Really appreciate if someone Help me out.
I shared my code in Snack Ps. it only works in ios and Android, does not work in web View.
This is my code
import React, { useState, useEffect, useCallback } from 'react';
import {
Dimensions, StatusBar, StyleSheet, Text,
TextInput, TouchableOpacity, View, Button
} from 'react-native';
import Constants from 'expo-constants';
import Mapview, { Marker, Callout, PROVIDER_GOOGLE } from 'react-native-maps'
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import datas from './datas.json'
// You can import from local files
import Animated from 'react-native-reanimated';
import BottomSheet from 'reanimated-bottom-sheet';
// or any pure javascript modules available in npm
export default function App() {
const sheetRef = React.useRef(null);
const renderContent = () => (
<View
style={{
backgroundColor: 'white',
padding: 16,
height: 450,
}}
>
<Text>Swipe down to close</Text>
<Button
title="Open Bottom Sheet"
onPress={() => sheetRef.current.snapTo(0)}
/>
</View>
);
const [state, setstate] = useState({
"latitude": 60.1098678,
"longitude": 24.7385084,
"latitudeDelta": 1,
"longitudeDelta": 1
});
useEffect(() => {
_onMapReady();
}, [_onMapReady]);
const _onMapReady = useCallback(async () => {
const { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== `granted`) {
// console.log(`Permisson Denied`);
}
const location = await Location.getCurrentPositionAsync({ "accuracy": Location.Accuracy.High });
setstate({
...state,
"latitude": location.coords.latitude,
"longitude": location.coords.longitude
});
}, [state]);
return (
<View style={styles.container}>
<Mapview
provider={PROVIDER_GOOGLE}
initialRegion={state}
showsIndoors={true}
showsMyLocationButton={true}
zoomControlEnabled={true}
zoomEnabled={true}
zoomTapEnabled={true}
showsScale={true}
showsBuildings={true}
showsUserLocation={true}
showsCompass={true}
onMapReady={_onMapReady}
style={styles.mapStyle}>
{
datas.data?.map((i) => {
return (
<Marker
coordinate={{
"latitude": i.location.lat,
"longitude": i.location.lng
}}
animation={true}
key={i.id}
>
<Callout
style={{ "width": 100, "height": 50 }}>
<View>
<Text>{i.Property}</Text>
</View>
</Callout>
</Marker>
);
})
}
</Mapview>
<BottomSheet
ref={sheetRef}
snapPoints={[450, 300, 0]}
borderRadius={10}
renderContent={renderContent}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
"flex": 1,
"alignItems": `center`,
"justifyContent": `center`
// position: 'absolute',
},
mapStyle: {
"height": Dimensions.get(`window`).height,
"width": Dimensions.get(`window`).width
},
});

Share image on whatsapp from react native android app

I am currently working on react-native photo sharing app for Android. Used native share method but it only share message and title. No options to share an image.
Looking after so many questions here couldn't find any straight forward way.
Please provide help.
This is the message I am getting Share awesome status on whatsapp using Khela #imageurl. Download #urltoplaystore
To share any image in React Native you are right you need to use the Share from react-native library itself, and you were wondering what is needed for an image, the answer it's really simple, you just need to use a Base64 image.
Check it out a working snack: snack.expo.io/#abrahamcalf/share-image
Wrap the code:
import * as React from 'react';
import {
Text,
View,
StyleSheet,
Image,
Share,
TouchableOpacity,
} from 'react-native';
export default class App extends React.Component {
state = {
cat: 'data:image/jpeg;base64,some-encoded-stuff;
};
handleSharePress = () => {
Share.share({
title: 'Share',
message: 'My amazing cat 😻',
url: this.state.cat,
});
};
render() {
return (
<View style={styles.container}>
<Image source={{ uri: this.state.cat }} style={styles.img} />
<TouchableOpacity onPress={this.handleSharePress}>
<Text>Share Image</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-around',
alignItems: 'center',
},
img: {
width: 200,
height: 300,
},
});
If you want to try something else, probably complex, I recommend to check out the react-native-share library from the React Native Community.
import Icon from 'react-native-vector-icons/Feather';
import Share from 'react-native-share';
import RNFetchBlob from 'rn-fetch-blob';
import React, {Component} from 'react';
const fs = RNFetchBlob.fs;
class ProductDetail extends Component {
constructor(props) {
super(props);
this.state = {};
}
shareTheProductDetails(imagesPath) {
let {productDetails} = this.state;
let imagePath = null;
RNFetchBlob.config({
fileCache: true,
})
.fetch('GET', imagesPath.image)
// the image is now dowloaded to device's storage
.then((resp) => {
// the image path you can use it directly with Image component
imagePath = resp.path();
return resp.readFile('base64');
})
.then((base64Data) => {
// here's base64 encoded image
var imageUrl = 'data:image/png;base64,' + base64Data;
let shareImage = {
title: productDetails.product_name, //string
message:
'Description ' +
productDetails.product_description +
' http://beparr.com/', //string
url: imageUrl,
// urls: [imageUrl, imageUrl], // eg.'http://img.gemejo.com/product/8c/099/cf53b3a6008136ef0882197d5f5.jpg',
};
Share.open(shareImage)
.then((res) => {
console.log(res);
})
.catch((err) => {
err && console.log(err);
});
// remove the file from storage
return fs.unlink(imagePath);
});
}
render() {
return (
<TouchableOpacity
style={{
borderWidth: 0,
left:(5),
top:(2),
}}
onPress={() =>
this.shareTheProductDetails(images)
}>
<Icon
style={{
left: moderateScale(10),
}}
name="share-2"
color={colors.colorBlack}
size={(20)}
/>
</TouchableOpacity>
)}
}

How to fetch random image from camera-roll using react native?

I have requirement where i need to get a random image every time when i click an button. I don't want picker to come up for the camera-roll with images, instead random image should selected from the camera folder and display in the image view.
I have followed the official FB tutorial of camera roll. Please find the code as below
_handleButtonPress = () => {
CameraRoll.getPhotos({
first: 20,
assetType: 'Photos',
})
.then(r => {
this.setState({ photos: r.edges });
})
.catch((err) => {
});
};
But this code will select the recently clicked images and display in the picker. Instead of to randomly select the uri of the image and display in the imageview. Any help is appreciated.
Regards,
Sharath
You essentially have the photos and all the necessary metadata once you set the state: this.setState({ photos: r.edges })
All you have to do is pick a random image from there. Here's how I did it:
import React, { Component } from 'react';
import {
StyleSheet,
View,
Image,
CameraRoll,
Button
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props)
this.state = {
img: null
}
}
getRandomImage = () => {
const fetchParams = {
first: 25,
}
CameraRoll.getPhotos(fetchParams)
.then(data => {
const assets = data.edges
const images = assets.map((asset) => asset.node.image)
const random = Math.floor(Math.random() * images.length)
this.setState({
img: images[random]
})
})
.catch(err => console.log)
}
render() {
return (
<View style={styles.container}>
{ this.state.img ?
<Image
style={styles.image}
source={{ uri: this.state.img.uri }}
/>
: null
}
<Button title="Get Random Image from CameraRoll" onPress={this.getRandomImage}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
image: {
width: '100%',
height: '75%',
margin: 10,
}
});

Categories

Resources