How can I take a screenshot (View) with a TouchableHighlight? - react-native

The Error has been resolved as per your guidelines.
But still can not take and save the screeshot of the desired ViewShot, where it has a react image.
I need to take and save the screeshot in the memory of my device.
Can you tell me if I'm on the right track or would I have another way to do it? Thanks!
Follow my current code.
import React, { Component } from 'react';
import { Text, View, Image, StyleSheet, TouchableHighlight } from 'react-native';
import { captureScreen } from "react-native-view-shot";
import ViewShot from "react-native-view-shot";
const zooMais = require('../imgs/zooMais.png');
const zooMenos = require('../imgs/zooMenos.png');
const imgScreeshot = require('../imgs/screeshot.png');
const btnZooMais = ()=>{
alert("Zoo Mais");
}
const btnZooMenos = ()=>{
alert("Zoo Menos");
}
const capitureScreen = ()=>{
captureScreen({
format: "jpg",
quality: 0.9,
}).then(
uri => console.log("Image saved to", uri),
error => console.error("Oops, snapshot failed", error)
);
}
export default class Monitor extends Component {
componentDidMount () {
this.refs.viewShot.capture().then(uri => {
console.log("do something with ", uri);
});
}
render() {
return (
<View>
<ViewShot ref="viewShot" options={{ format: "jpg", quality: 0.9 }} >
<Image source={{uri: 'https://facebook.github.io/react/logo-og.png'}} style={ style.video } />
</ViewShot>
<View style={style.menu}>
<View>
<TouchableHighlight onPress={ btnZooMais } >
<Image style={style.imgMenu} source={zooMais } />
</TouchableHighlight>
</View>
<View>
<TouchableHighlight onPress={ capitureScreen }>
<Image style={style.imgMenu} source={ imgScreeshot } />
</TouchableHighlight >
</View>
<View>
<TouchableHighlight onPress={ btnZooMenos } >
<Image style={style.imgMenu} source={ zooMenos } />
</TouchableHighlight>
</View>
</View>
</View>
);
}
}
const style = StyleSheet.create({
corpo: {
},
menu:{
flexDirection:'row',
justifyContent: 'space-between'
},
imgMenu:{
//margin: 15
},
video: {
width: 400,
height: 450
}
});

Looks like you may not have either linked the package or rebuilt the app after linking.
Try
$ react-native link react-native-view-shot
$ react-native run-{ios|android}

Related

How do you get 1 specific value from a prop in expo?

I've been trying to pass up this prop from CameraButton.js file that gives the UI of an image that was taken but whenever I activate the prop in the AddPost.js, it gives me all the values but when I try to get the singular value of the image like using console.log(props.route.params.image) and gives error undefined is not an object
enter image description here
but it works perfectly when export default function console.log(props.route.params) and shows
enter image description here
AddPost.JS
import { useNavigation } from "#react-navigation/core";
import React from 'react'
import {useState} from "react";
import { View, TextInput, Button } from 'react-native'
export default function AddPost(props) {
console.log(props);
const navigation = useNavigation();
const [caption, setCaption] = useState("")
const uploadImage = async () => {
const response = await fetch(uri)
}
return (
<View style={{flex: 1}}>
<TextInput
placeholder="Whats on your mind Edgers navars"
onChangeText={(caption) => setCaption(caption)}
/>
<Button title = "Take A Photo" onPress={() => navigation.navigate("CameraButton")}
/>
<Button title = "Save" onPress={() => uploadImage()}
/>
</View>
)
}
CameraButton.Js
import { Camera, CameraType } from 'expo-camera';
import { useNavigation } from "#react-navigation/core";
import { useState } from 'react';
import { Button, StyleSheet, Text, TouchableOpacity, View, Image } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
export default function App() {
const navigation = useNavigation();
const [type, setType] = useState(Camera.Constants.Type.back)
const [permission, requestPermission] = Camera.useCameraPermissions();
const [image, setImage] = useState(null);
const [camera, setCamera] = useState(null);
const takePicture = async () => {
if(camera){
const data = await camera.takePictureAsync(null);
setImage(data.uri);
}
}
if (!permission) {
// Camera permissions are still loading
return <View />;
}
if (!permission.granted) {
// Camera permissions are not granted yet
return (
<View style={styles.container}>
<Text style={{ textAlign: 'center' }}>
We need your permission to show the camera
</Text>
<Button onPress={requestPermission} title="grant permission" />
</View>
);
}
function toggleCameraType() {
setType((current) => (
current === Camera.Constants.Type.back ? Camera.Constants.Type.front : Camera.Constants.Type.back
));
}
// No permissions request is necessary for launching the image library
let openImagePickerAsync = async () => {
let permissionResult = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (permissionResult.granted === false) {
alert("Permission to access camera roll is required!");
return;
}
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
setImage(result.uri);
}
}
return (
<View style={styles.container}>
<Camera ref={ref => setCamera(ref)} style={styles.camera} type={type}>
<View style={styles.buttonContainer}>
<TouchableOpacity
style={styles.button}
onPress={toggleCameraType}>
<Text style={styles.text}>Flip Camera</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => takePicture()}>
<Text style={styles.text}>Take Picture</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={openImagePickerAsync}>
<Text style={styles.text}>Choose Picture</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('AddPost', {image})}>
<Text style={styles.text}>Save Picture</Text>
</TouchableOpacity>
</View>
</Camera>
{image &&<Image source={{uri: image}}style={styles.camera}/>}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
camera: {
flex: 1,
},
buttonContainer: {
flex: 1,
flexDirection: 'row',
backgroundColor: 'transparent',
margin: 64,
},
button: {
flex: 1,
alignSelf: 'flex-end',
alignItems: 'center',
},
text: {
fontSize: 24,
fontWeight: 'bold',
color: 'white',
},
});
You have to get the uri from the route object.
const response = await fetch(props.route.params?.image)
In you file CameraButton.js set the navigation for this:
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('AddPost', {
image: image
})}>
<Text style={styles.text}>Save Picture</Text>
</TouchableOpacity>
Be sure that the state image contains only the uri and not and object
Try props[0].route.params.image.

TypeError: null is not an object (evaluating 'RNPaypal.requestOneTimePayment')

I have installed react-native-paypal in my React Native project built using expo. But while running project I am facing error like this. I have also run "react-native link" but the error remains there.
Here is my code:
import { TouchableOpacity } from "react-native";
import _ from "lodash";
import {
View,
Text,
List,
ListItem,
Body,
Left,
Thumbnail,
Header,
} from "native-base";
import appStyles from "../../theme/appStyles";
import { Colors, Layout } from "../../constants";
import styles from "./styles";
import Icon from "react-native-vector-icons/FontAwesome5";
import PayPal from "react-native-paypal";
class HomeFilterHeader extends React.Component {
constructor(props) {
super(props);
}
goToPaypal = async () => {
await this.props.navigation.closeDrawer();
PayPal.paymentRequest({
clientId:
"AbyfNDFV53djg6w4yYgiug_JaDfBSUiYI7o6NM9HE1CQ_qk9XxbUX0nwcPXXQHaNAWYtDfphQtWB3q4R",
environment: PayPalAndroid.SANDBOX,
price: "42.00",
currency: "USD",
description: "PayPal Test",
})
.then((confirm, payment) => console.log("Paid"))
.catch((error_code) => console.error("Failed to pay through PayPal"));
}
render() {
const { user, userBalance } = this.props;
return (
<Header style={styles.header}>
<View style={[appStyles.row, { paddingTop: Layout.fourthIndent }]}>
<List>
<ListItem
avatar
noBorder
onPress={() => this.props.onOpenProfile()}
>
<Left>
<Thumbnail
source={{ uri: user && user.user && user.user.image }}
/>
</Left>
<Body>
<Text style={appStyles.textBlack}>
{user && user.user && user.user.user_name}
</Text>
<Text
style={{
color: Colors.secondary,
fontSize: Layout.halfIndent,
}}
>
{" "}
<Icon
name="coins"
size={Layout.halfIndent}
color={Colors.secondary}
style={{ paddingRight: 1 }}
/>{" "}
{userBalance &&
userBalance.user_balance &&
userBalance.user_balance.point_balance}{" "}
/ ${" "}
{userBalance &&
userBalance.user_balance &&
_.round(userBalance.user_balance.winning_amount, 2)}
</Text>
<TouchableOpacity
style={styles.addFundsButton}
onPress={() => this.goToPaypal()}
>
<Text style={appStyles.textWhite}>Add Funds</Text>
</TouchableOpacity>
</Body>
</ListItem>
</List>
</View>
</Header>
);
}
}
// Exports
export default HomeFilterHeader;

Creating Drop down list in react native

I am creating a UI for Coronavirus tracking. So I need a drop-down list to fetch data of different countries on clicking specific country.I am sharing the code segment.Any help would be appreciable.
import React from "react";
import Axios from "axios";
import { StyleSheet, View, ImageBackground, Text, Image, Picker } from "react-native";
import { Dropdown } from "react-native-material-dropdown";
export default class App extends React.Component {
constructor(props) {
super(props);
this.getCountryData = this.getCountryData.bind(this);
}
state = {
confirmed: 0,
recovered: 0,
deaths: 0,
countries: []
}
componentDidMount() {
this.getData();
}
async getData() {
const resApi = await Axios.get("https://covid19.mathdro.id/api");
const resCountries = await Axios.get("https://covid19.mathdro.id/api/countries");
const countries = [];
for (var i=0; i < resCountries.data.countries.length; i++) {
countries.push(resCountries.data.countries[i].name);
}
this.setState({
confirmed: resApi.data.confirmed.value,
recovered: resApi.data.recovered.value,
deaths: resApi.data.deaths.value,
countries
});
}
async getCountryData(event){
try {
const res = await Axios.get(`https://covid19.mathdro.id/api/countries/${event.target.value}`);
this.setState({
confirmed: res.data.confirmed.value,
recovered: res.data.recovered.value,
deaths: res.data.deaths.value
})}
catch (err) {
if(err.response.status === 404)
this.setState({
confirmed: "No data available",
recovered: "No data available",
deaths: "No data available"
})
}
}
renderCountryOptions() {
return this.state.countries.map((name, i) => {
return <Text key={name}>{name}</Text>
});
}
render() {
return (
<View style={styles.container}>
<View style={{justifyContent: 'center',alignItems: 'center'}}>
<View style={{height: 150, top:29,width:900, backgroundColor: 'steelblue'}} />
<Text style={styles.text}>COVID-19 Cases Overview</Text>
</View>
<Image
source={require("./assets/Covid-19.jpg")}
resizeMode="contain"
style={styles.image}
>
</Image>
<Text style={styles.text1}>Global Data</Text>
<View style={styles.dropDown}>
<Dropdown onChange={this.getCountryData}>
{this.renderCountryOptions()}
</Dropdown>
</View>
<View>
<View style={styles.boxConfirmed}>
<Text>Confirmed </Text>
<Text>{this.state.confirmed}</Text>
</View>
<View style={styles.boxRecovered}>
<Text>Recovered</Text>
<Text>{this.state.recovered}</Text>
</View>
<View style={styles.boxDeaths}>
<Text> Deaths</Text>
<Text>{this.state.deaths}</Text>
</View>
</View>
</View>
);
}
}
I am unable to extract data of individual country. Please suggest me how I can use Dropdown in React Native
You can use react native picker from react native community for the task...
<Picker
selectedValue={this.state.language}
style={{height: 50, width: 100}}
onValueChange={(itemValue, itemIndex) =>
this.setState({language: itemValue})
}>
this.state.list.map((val) => {
<Picker.Item label=val value=val />
})

How do I upload an image taken React-Native-camera to Firebase storage?

I want upload image taken with react-native-camera to https://github.com/invertase/react-native-firebase storage on RN
I can't upload image.
I tried image-picker-library and did work.
import React, { Component } from 'react';
import {Image, View, Text, StyleSheet, Dimensions,TouchableOpacity} from 'react-native'
import { RNCamera } from 'react-native-camera';
import {strings} from '../Lang/Strings';
import { Actions } from 'react-native-router-flux';
const { width, height } = Dimensions.get('window');
export default class ScanPage extends Component {
constructor(props) {
super(props);
this.state = {
takePicture = async () => {
if (this.camera) {
const options = { quality: 0.5, base64: true }
const data = await this.camera.takePictureAsync(options)
Actions.ProfilePage({imagePath:data.uri,
selectedIndex:this.state.selectedIndex,
shapes:this.state.shapes });
this.uploadPhoto(data);
};
};
render() {
const {selectedIndex, images, shapes} = this.state;
return(
<View style={styles.container}>
<RNCamera
ref={ref => {
this.camera = ref;
}}
style={styles.preview}
type={RNCamera.Constants.Type.front}
permissionDialogTitle={'Permission to use camera'}
permissionDialogMessage={'We need your permission to use your camera phone'} />
<View style={{flex:1,justifyContent:'center' ,alignItems:'center'}}>
<View style={{marginTop:120}}>
<Image source={images[selectedIndex]} >
</Image>
</View>
</View>
<View style={styles.buttonSection}>
<TouchableOpacity onPress={this._TogglePrev}>
<View style={styles.buttons}>
<Text style={{textAlign:'center',color: 'white'}}>
{strings.back}
</Text>
</View>
</TouchableOpacity>
<View style={{alignItems:'center', justifyContent:'center',
height:height*0.04}}>
<Text style ={{color:'white',textAlign:'center'}}>{shapes[selectedIndex]} </Text>
</View>
<TouchableOpacity onPress={this._ToggleNext}>
<View style={styles.buttons}>
<Text style={{textAlign:'center', color: 'white'}}>
{strings.next}
</Text>
</View>
</TouchableOpacity>
</View>
<View style={{alignItems:'center', justifyContent:'center',
backgroundColor:'#D9E6FF',height:height*0.001,width:width*1}}>
<Text style ={{color:'white',textAlign:'center'}}> </Text>
</View>
<View style={{ flex: 0, flexDirection: 'row', justifyContent: 'center'}}>
<TouchableOpacity onPress={this.takePicture.bind(this)} style={styles.capture}
>
<View style={{
backgroundColor: 'white',
borderRadius: (height*0.16)/2,
padding: 15,
alignSelf: 'center',
margin: 25,
height:height*0.085,
width:width*0.16,
justifyContent:'center',
alignItems:'center',
borderWidth:0.9,
borderColor:'#D9E6FF',}}></View>
</TouchableOpacity>
</View>
</View>
);
}
takePicture = async function() {
if (this.camera) {
const options = { quality: 0.5, base64: true };
const data = await this.camera.takePictureAsync(options);
Actions.ProfilePage({imagePath:data.uri,
selectedIndex:this.state.selectedIndex,
shapes:this.state.shapes
});
}
};
}
I didn't upload firebase,
versions
react: 16.4.1,
react-native: 0.56.0,
react-native-camera:1.12.0,
react-native-firebase:5.2.3
react-native-router-flux:4.0.1
Can't believe I've figured it out >.<
if you've set up your project correctly to include firebase
takePicture = async() => {
if (this.camera) {
// this code takes the picture
const options = { quality: 0.5, base64: true };
const data = await this.camera.takePictureAsync(options);
// open debug to see the uri of image
console.log(data.uri);
// send your data.uri off to firebase! :D
const processed = await firebase.vision().imageLabelerProcessImage(data.uri, {
confidenceThreshold: 0.8,
});
//Look at your debugger again
console.log('Label: ', processed);
}
};
I hope this helps!
_publish = async () => {
const imageuri= this.state.imagePath;
//this is where + how you want your image to be stored into
const refFile= firebase.storage().ref().child('profile_pic');
refFile.putFile(imageuri)
.catch(error => {
console.log(error);
// Alert.alert('Hey', error);
});
}
hope it helps!

Capture view-shot and save to device - React Native

I am developing an application where I have a button (TouchableHighlight) when pressing this button it is necessary to capture a screeshot of the current screen and save the file in the device.
My code does not show error, but when I press the button (TouchableHighlight) I get the message:
Image saved to file: ///data/user/0/com.appcamerav4/cache/ReactNative-snapshot-image8525057299267209213.jpg through Remote JS Debugging .
I can not open this directory and need to save the image to the device.
I'm new to react-native.
Follow my code below:
import React, { Component } from 'react';
import { Text, View, Image, StyleSheet, TouchableHighlight, WebView, StatusBar, Button } from 'react-native';
import { captureScreen } from "react-native-view-shot";
const zooMais = require('../imgs/zooMais.png');
const zooMenos = require('../imgs/zooMenos.png');
const imgScreeshot = require('../imgs/screeshot.png');
const btnZooMais = ()=>{
alert("Zoo Mais");
console.log("Zoom +");
}
const btnZooMenos = ()=>{
alert("Zoo Menos");
console.log("Zoom +");
}
const capitureScreen = ()=>{
captureScreen({
format: "jpg",
quality: 0.8,
}).then(
uri => console.log("Image saved to", uri),
error => console.error("Oops, snapshot failed", error)
);
}
export default class Monitor extends Component {
render() {
return (
<View style={ style.viewPrincipal }>
<StatusBar hidden />
<View style={ style.viewImagem } >
<WebView
style={style.video}
automaticallyAdjustContentInsets={true}
scalesPageToFit={true}
startInLoadingState={false}
contentInset={{top: 0, right: 0, left: 0, bottom: 0}}
scrollEnabled={true}
source={{uri: 'https://facebook.github.io/react/logo-og.png'}}
onNavigationStateChange = {this.handleNavigationStateChange}
/>
</View>
<View style={ style.viewRodape }>
<View style={style.viewMenu}>
<View >
<TouchableHighlight onPress={ btnZooMais } >
<Image style={style.imgMenu} source={zooMais } />
</TouchableHighlight>
</View>
<View>
<TouchableHighlight onPress={ capitureScreen }>
<Image style={style.imgMenu} source={ imgScreeshot } />
</TouchableHighlight >
</View>
<View>
<TouchableHighlight onPress={ btnZooMenos } >
<Image style={style.imgMenu} source={ zooMenos } />
</TouchableHighlight>
</View>
</View>
</View>
</View>
);
}
}
const style = StyleSheet.create({
viewPrincipal:{
flex: 1
},
viewImagem:{
flex:10,
justifyContent:'center',
alignItems:'stretch'
},
viewRodape:{
flex:1.3
},
viewMenu:{
flexDirection:'row',
justifyContent: 'space-between'
},
imgMenu:{
margin: 0,
marginBottom:0
},
video:{
flex:1
}
});
Make sure react-native-view-shot is correctly linked in XCode (might require a manual installation,
refer to React Native doc).
import React, { useRef } from "react"; // import useRef hook on top
const cardRef = useRef(); // Use this hook inside your func. component *important
// Define a function like this
const saveAsImage = async () => {
try {
const result = await captureRef(cardRef, {
result: "tmpfile",
quality: 1,
format: "png",
});
MediaLibrary.saveToLibraryAsync(result);
} catch (e) {
console.log(e);
}
};
Apply a prop eg. parentRef={cardRef} to your component, make sure the ref name matches which in this case is "cardRef".
Give any Button/TouchableOpacity
onPress={() => {saveAsImage();}}
To solve this problem you have to go on your App permission on your real mobile and allow for camera storage then you can easily save your ViewShot on Your Mobile.
go to App Permisssion in your App.info
allow Camera accesss storage
To save the screenshot to the camera roll, use this one: https://facebook.github.io/react-native/docs/cameraroll.html#savetocameraroll
More info: https://github.com/gre/react-native-view-shot Check the FAQ section