Uploading an image in react-native using react-native-image-picker - reactjs

I have just initialized a basic react-native project and its running in the emulator. I have as well installed this package https://github.com/react-community/react-native-image-picker
and i am trying to upload an image. The code is simple as i have just added some code to handle image upload
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Button,
Text,
Image,
Alert,
View
} from 'react-native';
var ImagePicker = require('react-native-image-picker');
var options = {
title: 'Select Avatar',
customButtons: [
{name: 'fb', title: 'Choose Photo from Facebook'},
],
storageOptions: {
skipBackup: true,
path: 'images'
}
};
const onPressLearnMore = () => {
ImagePicker.launchImageLibrary(options, (response) => {
let source = { uri: response.uri };
this.setState({
avatarSource: source
});
});
//Alert.alert('Button has been pressed!');
};
export default class AwesomeProject extends Component {
constructor() {
super()
this.state = {
avatarSource: 'image.jpg'
}
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Button onPress={onPressLearnMore} title="Upload Image" color="#841584" accessibilityLabel="Learn more about this purple button" />
<Image source={this.state.avatarSource} style={styles.uploadAvatar} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
I get this error when i run this on the emulator
undefined is not a function (evaluating '_this.setState({
avatarSource: source
})')
<unknown>
index.android.bundle?platform=android&dev=true&hot=false&minify=false:1274:19
__invokeCallback
index.android.bundle?platform=android&dev=true&hot=false&minify=false:4818:21
<unknown>
index.android.bundle?platform=android&dev=true&hot=false&minify=false:4664:32
__guard
index.android.bundle?platform=android&dev=true&hot=false&minify=false:4753:11
invokeCallbackAndReturnFlushedQueue
index.android.bundle?platform=android&dev=true&hot=false&minify=false:4663:19

You should write the function onPressLearnMore inside your AwesomeProject component, and don't forget to bind in order to use this
export default class AwesomeProject extends Component {
constructor(){
...
this.onPressLearnMore = this.onPressLearnMore.bind(this)
}
onPressLearnMore(){
//you can use this.setState
}
render(){
...
}
}

Related

Unhandled promise rejection: FirebaseError: Function addDoc() called with invalid data. Unsupported field value: a custom SyntheticEvent object

I'm coding a react native app that stores info in firebase. This code should create a new collection but I get the error
[Unhandled promise rejection: FirebaseError: Function addDoc() called with invalid data. Unsupported field value: a custom SyntheticEvent object (found in field name in document events/VgAsJLRAtFmuhkJ1zNxz)]
I got it down for using the state as a variable when sending the query to firebase. If I change it to a string it works.
import { Text, StyleSheet, View, Button } from "react-native";
import React, { Component } from "react";
import MainStyles from "../../styles/main.styles";
import { TextInput } from "react-native-paper";
import { db } from "../../FireBase/auth.firebase";
import { collection, getDocs, addDoc } from "firebase/firestore";
export default class verified extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
};
}
//update in state the values
upName = (value) => {
this.setState({ name: value });
};
//creats the document
creat = async () => {
//The error is here. I get it when using state as a variable
await addDoc(collection(db, "events"), { name: this.state.name });
console.log("yes");
};
render() {
return (
<View style={MainStyles.container}>
<Text style={styles._color}>Creat </Text>
<View style={styles.inputsContainers}>
<TextInput
placeholder="Name"
style={styles.TextIn}
onChange={this.upName}
value={this.state.name}
></TextInput>
</View>
<Button
style={{ fontSize: 20, color: "green" }}
styleDisabled={{ color: "red" }}
title="Press Me"
onPress={this.creat}
/>
</View>
);
}
}
const styles = StyleSheet.create({
_color: {
color: "white",
},
TextIn: {
height: 40,
backgroundColor: "#242424",
paddingTop: 10,
color: "#ffffff",
flex: 1,
},
inputsContainers: {
padding: 20,
flexDirection: "row",
width: "85%",
backgroundColor: "transparent",
},
});

Google SignIn from Reactive Native giving TypeError - Expo

I am trying to create a simple React Native app with Google OAuth Login.
I have created credentials in google and inputted the same in the app.js file.
The app starts in the android emulator and when i click sign in with google it gives the error in console:
"error [TypeError: undefined is not an object (evaluating
'_expo.default.Google')]"
I have no idea how to solve this.
This is my app.js
import React from "react"
import { StyleSheet, Text, View, Image, Button } from "react-native"
import Expo from "expo"
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
signedIn: false,
name: "",
photoUrl: ""
}
}
signIn = async () => {
try {
const result = await Expo.Google.logInAsync({
androidClientId:
"**********",
//iosClientId: YOUR_CLIENT_ID_HERE, <-- if you use iOS
scopes: ["profile", "email"]
})
if (result.type === "success") {
this.setState({
signedIn: true,
name: result.user.name,
photoUrl: result.user.photoUrl
})
} else {
console.log("cancelled")
}
} catch (e) {
console.log("error", e)
}
}
render() {
return (
<View style={styles.container}>
{this.state.signedIn ? (
<LoggedInPage name={this.state.name} photoUrl={this.state.photoUrl} />
) : (
<LoginPage signIn={this.signIn} />
)}
</View>
)
}
}
const LoginPage = props => {
return (
<View>
<Text style={styles.header}>Sign In With Google</Text>
<Button title="Sign in with Google" onPress={() => props.signIn()} />
</View>
)
}
const LoggedInPage = props => {
return (
<View style={styles.container}>
<Text style={styles.header}>Welcome:{props.name}</Text>
<Image style={styles.image} source={{ uri: props.photoUrl }} />
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center"
},
header: {
fontSize: 25
},
image: {
marginTop: 15,
width: 150,
height: 150,
borderColor: "rgba(0,0,0,0.2)",
borderWidth: 3,
borderRadius: 150
}
})
Any help , suggestions ?
Thanks a lot !
This example from the docs no longer works as a result of changes made in the latest versions of expo CLI.
The Google app auth package has been moved to a standalone package - expo-google-app-auth and as a result, you need to import the Google object from that package.
below are some steps to make sure you are referencing the correct package
make sure that the expo-google-app-auth is installed (you can use expo install expo-google-app-auth )
then you should import the Google object using: import * as Google from 'expo-google-app-auth'
then you can use the logInAsync() function like so:
...
const result = await Google.logInAsync({
...
})
I was able to get rid of this issue by downgrading to SDK expo version 31.0.0.
I had the same issue with the google-expo-sign-in module. Fixed it by using app-auth instead.

Why won't my Custom React Native Component Import Correctly

Currently, I have a simple React Native Expo app setup. I have two components App and QRreader.
I am trying to import the QRreader component into my main App component.
The Main App component code...
import React, { Component } from 'react';
import { Button, Text, View, StyleSheet } from 'react-native';
import { Constants, WebBrowser } from 'expo';
import QRreader from './qr';
export default class App extends Component {
state = {
result: null,
};
render() {
return (
<View style={styles.container}>
<QRreader/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
The QR component code...
import React, { Component } from 'react';
import { Text, View, StyleSheet, Alert } from 'react-native';
import { Constants, BarCodeScanner, Permissions } from 'expo';
export default class QRreader extends Component {
state = {
hasCameraPermission: null
};
componentDidMount() {
this._requestCameraPermission();
}
_requestCameraPermission = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
this.setState({
hasCameraPermission: status === 'granted',
});
};
_handleBarCodeRead = data => {
Alert.alert(
'Scan successful!',
JSON.stringify(data)
);
};
render() {
return (
<View style={styles.container}>
{this.state.hasCameraPermission === null ?
<Text>Requesting for camera permission</Text> :
this.state.hasCameraPermission === false ?
<Text>Camera permission is not granted</Text> :
<BarCodeScanner
onBarCodeRead={this._handleBarCodeRead}
style={{ height: 200, width: 200 }}
/>
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
}
});
I tried different variations of the import using "./" "." "qr.js" "qr"
Im getting an error Unable to resolve module "qr.js" Module does not exist in the main module map.
My file structure is Here
You haven't registered your main module yet.
AppRegistry.registerComponent('Main', () => App); Please add this line to the bottom of your class and check if the problem persists.
hmm...so it looked like I had to restart the Expo project for it to work without adding any additional code.
Just out of curiosity?
Where would I add AppRegistry.registerComponent('Main', () => App); exactly? and why would I have to do this?

undefined is not a function evaluating _this2.props.navigator.push

I am trying to scaffold a simple drawer and navigation in react-native.
As you can see I import the drawer and then I instantiate the Navigator below the Toolbar.
I want to be able to change the route from the AppDrawer but the only thing I get after the button click is
*undefined is not a function (evaluating '_this2.props.navigator.push({ id: 'component5' })') *
Note: I have not attached Component 3 or 5 code because they are simple text renders.
index.android.js
import React, {Component} from 'react';
import {AppRegistry, StyleSheet, Text, View, Navigator, ToolbarAndroid} from 'react-native';
import Component3 from "./app/components/Component3/Component3";
import Component5 from "./app/components/Component5/Component5";
import MyAppDrawer from "./app/components/Miscellaneous/AppDrawer";
import Drawer from 'react-native-drawer';
const drawerStyles = {
drawer: {
shadowColor: "#343477",
shadowOpacity: 0.8,
shadowRadius: 0,
}
}
export default class ReactTest extends Component {
constructor(props, context) {
super(props, context);
this.state = {
drawerType: 'overlay',
openDrawerOffset: 50,
closedDrawerOffset: 0,
panOpenMask: .1,
panCloseMask: .9,
relativeDrag: false,
panThreshold: .25,
tweenHandlerOn: false,
tweenDuration: 350,
tweenEasing: 'linear',
disabled: false,
tweenHandlerPreset: null,
acceptDoubleTap: false,
acceptTap: false,
acceptPan: true,
tapToClose: false,
negotiatePan: false,
rightSide: false,
};
}
openDrawer() {
this.drawer.open()
}
renderScene(route, navigator) {
switch (route.id) {
case 'component2':
return (<Component2 navigator={navigator}/>)
case 'component3':
return (<Component3 navigator={navigator}/>)
case 'component4':
return (<Component4 navigator={navigator}/>)
case 'component5':
return (<Component5 navigator={navigator} title="component5"/>)
case 'component6':
return (<Component6 user={route.user} navigator={navigator} title="component6"/>)
}
}
onActionSelected(position) {
console.log("Settings clicked");
}
onIconClicked(position) {
console.log("App Drawer clicked");
}
render() {
var controlPanel = <MyAppDrawer navigator={navigator} closeDrawer={() => {
this.drawer.close();
}}/>
return (
<View style={styles.containerToolbar}>
<Drawer
ref={c => this.drawer = c}
type={this.state.drawerType}
animation={this.state.animation}
captureGestures={true}
openDrawerOffset={this.state.openDrawerOffset}
closedDrawerOffset={this.state.closedDrawerOffset}
panOpenMask={this.state.panOpenMask}
//panCloseMask={this.state.panCloseMask}
relativeDrag={this.state.relativeDrag}
panThreshold={this.state.panThreshold}
content={controlPanel}
styles={drawerStyles}
disabled={this.state.disabled}
// tweenHandler={this.tweenHandler.bind(this)}
// tweenDuration={this.state.tweenDuration}
// tweenEasing={this.state.tweenEasing}
acceptDoubleTap={this.state.acceptDoubleTap}
acceptTap={this.state.acceptTap}
acceptPan={this.state.acceptPan}
tapToClose={this.state.tapToClose}
negotiatePan={this.state.negotiatePan}
// changeVal={this.state.changeVal}
side={this.state.rightSide ? 'right' : 'left'}
>
<ToolbarAndroid
style={styles.toolbar}
title="MyApp"
// logo={require('./dummy_logo.png')}
navIcon={require("./navigation_icon.png")}
onActionSelected={this.onActionSelected}
onIconClicked={this.openDrawer.bind(this)}
titleColor="black"
actions={[
{title: "Log out", show: "never"}
]}
/>
<Navigator
style={styles.container}
initialRoute={{id: 'component3'}}
renderScene={this.renderScene}/>
</Drawer>
</View>
);
}
}
const styles = StyleSheet.create({
containerToolbar: {
flex: 1,
//justifyContent: 'center',
justifyContent: 'flex-start',
// https://github.com/facebook/react-native/issues/2957#event-417214498
alignItems: 'stretch',
backgroundColor: '#F5FCFF',
},
toolbar: {
backgroundColor: '#e9eaed',
height: 56,
},
});
AppRegistry.registerComponent('ReactTest', () => ReactTest);
AppDrawer.js
import React, {Component} from 'react';
import {View, Text, Button, Navigator} from 'react-native';
import styles from './styles';
export default class AppDrawer extends Component {
constructor() {
super();
}
render() {
return (
<View style={styles.controlPanel}>
<Text style={styles.controlPanelWelcome}>
Control Panel
</Text>
<Button
onPress={() => {
console.log("pressed");
this.props.navigator.push({
id: 'component5',
});
}}
title="Component 5"
/>
</View>
)
}
}
Since you don't have MyAppDrawer inside your renderScene function, you don't have access to the navigator. You would need to add a ref and use that to get the navigator:
Add ref={navigator => this.navigator = navigator} to your Navigator component, then you can do
<MyAppDrawer navigator={this.navigator} closeDrawer={() => {
this.drawer.close();
}}/>

Module Error Requiring unknown module

Hello am having a problem I am using react native am a newbie and I am creating a app that has some tabs but what i want is when i click the tab each as its own navigation bar.
I follow [AppCoda Example][1] but i notice that code base is different from the new code base react native. my code is bellow. Remember am trying to get a Nav bar for each tabs an i created a folder structure to require each tab in but am getting that unknown module when i know its there. Just to add if i add the same code which was in sub folder in the index.os.js it works look below:
'use strict';
var React = require('react-native');
var SearchButton = require('./app/components/buttons/searchButton');
var CameraButton = require('./app/components/buttons/cameraButton');
var ProfileButton = require('./app/components/buttons/profileButton');
var ContactButton = require('./app/components/buttons/contactButton');
var {
AppRegistry,
TabBarIOS,
NavigatorIOS,
StyleSheet,
Text,
View
} = React;
class AwesomeProject extends React.Component{
constructor(props) {
super(props);
this.state = {
selectedTab: 'Search'
};
}
render() {
return (
<TabBarIOS selectedTab={this.state.selectedTab} barTintColor="darkslateblue">
<TabBarIOS.Item
selected={this.state.selectedTab === 'Search'}
systemIcon="search"
onPress={() => {
this.setState({
selectedTab: 'Search'
});
}} style={styles.container} >
<SearchButton/>
</TabBarIOS.Item>
<TabBarIOS.Item systemIcon="bookmarks"
selected={this.state.selectedTab === 'Camera'}
icon={{uri:'Camera'}}
onPress={() => {
this.setState({
selectedTab: 'Camera'
});
}}>
<CameraButton/>
</TabBarIOS.Item>
<TabBarIOS.Item systemIcon="history"
selected={this.state.selectedTab === 'Profile'}
icon={{uri:'Profile'}}
onPress={() => {
this.setState({
selectedTab: 'Profile'
});
}}>
<ProfileButton/>
</TabBarIOS.Item>
<TabBarIOS.Item systemIcon="contacts"
selected={this.state.selectedTab === 'Contacts'}
icon={{uri:'Contacts'}}
onPress={() => {
this.setState({
selectedTab: 'Contacts'
});
}}>
<ContactButton/>
</TabBarIOS.Item>
</TabBarIOS>
);
}
};
var styles = StyleSheet.create({
navigator: {
flex: 1,
},
tabContent: {
flex: 1,
alignItems: 'center', },
tabText: {
color: 'white',
margin: 50, },
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
Now in the search button which should get the search title from a navigation folder thats where the problem is its saying unknown module
'use strict';
var React = require('react-native');
var searchTitle = require('./app/components/navigation/searchTitle');
var {
StyleSheet,
View,
NavigatorIOS,
Text
} = React
var styles = StyleSheet.create({
navigator: {
flex: 1
}
}
);
class Search extends React.Component{
render() {
return (
<NavigatorIOS
style={styles.navigator}
initialRoute={{
title: 'SomeTitle',
component: searchTitle
}}/>
);
}
}
module.exports = Search;
can some one help me with this.
You are asking require to search a relative path. From your examples I see that searchButton is in ./app/components/buttons/ and searchTitle is in ./app/components/navigation/, so if you want to require searchTitle from searchButton the path you need to specify is ../navigation/searchTitle.
var back_bg = require('./../img/menu.png');

Resources