The error:
ESLint: App.js (22:21) Parsing error: Unexpected token, expected ";"
20 | export default function App() {
21 |
> 22 | constructor(props){
| ^
23 | super(props)
24 |
25 | this.state = ({ (null)
Code:
import React from 'react';
import { StyleSheet, Image, Text, View } from 'react-native';
import { Container, Content, Header, Form, Input, Item, Button, Label, } from 'native-base';
import * as firebase from 'firebase';
var firebaseConfig = {
apiKey: "AIzaSyB387ecmvoIcHvboydLrxL_vwBJqWHhXGw",
authDomain: "shootgeorgiaapp.firebaseapp.com",
databaseURL: "https://shootgeorgiaapp.firebaseio.com",
projectId: "shootgeorgiaapp",
storageBucket: "shootgeorgiaapp.appspot.com"
};
if (!firebase.apps.length){
firebase.initializeApp(firebaseConfig);
}
export default function App() {
constructor(props){
super(props)
this.state = ({
email:'',
password:''
})
}
signUpUser = (email,password) =>{
try{
if(this.state.password.length<6){
alert("გთხოვთ მიუთთოთ 6-ზე მეტ ციფრიანი პაროლი")
return;
}
firebase.auth().createUserWithEmailAndPassword(email,password)
}
catch(error){
console.log(error.toString())
}
}
logInUser = (email,password) =>{
}
return (
<Container style={styles.container}>
<Form>
<Image
style={{height:170 , width:170, alignItems: 'center',}}
source={require('./img/logo.png')}
/>
<Item floatingLabel>
<Label>Email</Label>
<Input
autoCorrect={false}
autoCapitalize="none"
onChangeText={(email) => this.setState({email})}
/>
</Item>
<Item floatingLabel>
<Label>Password</Label>
<Input
secureTextEntry={true}
autoCorrect={false}
autoCapitalize="none"
onChangeText={(password) => this.setState({password})}
/>
</Item>
<Button style={{marginTop:10} }
full
rounded
success
onPress={() => this.logInUser(this.state.email,this.state.password)}
>
<Text style={{color:'white'}}>Log in</Text>
</Button>
<Button style={{marginTop:10} }
full
rounded
primary
onPress={() => this.signUpUser(this.state.email,this.state.password)}
>
<Text style={{color:'white'}}>Sign in</Text>
</Button>
</Form>
</Container>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
justifyContent: 'center',
padding: 10,
},
});
I tried thousands of things but nothing works.
your declaring a function 'App' and treating it as a class. A simple solution is you use classes instead
export default class App extends Component{
//
}
in order to inherit what you're looking for.
Security flag: don't post your api keys anywhere in the internet or sensitive information
Related
Peace...
I'm trying to make a text input component which receives input from user like below:
All inputs from user...
//AppTextInput (main supplier)
import React, { useState } from 'react';
import { StyleSheet, TextInput, View } from 'react-native';
import { MaterialCommunityIcons } from '#expo/vector-icons';
import defaultStyles from '../config/styles';
export default function AppTextInput({ icon, ...otherProps }) {
// const [firstName, setFirstName] = useState('');
// const [isNew, setIsNew] = useState(false);
return (
<View style={styles.container}>
{icon && <MaterialCommunityIcons name={icon} size={20}
color={defaultStyles.colors.medium} style={styles.icon}
/>}
<TextInput style={defaultStyles.text} {...otherProps}
placeholderTextColor={defaultStyles.colors.medium}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
backgroundColor: defaultStyles.colors.light,
borderRadius: 25,
flexDirection: 'row',
width: '100%',
padding: 15,
marginVertical: 10,
},
icon: {
marginRight: 10,
alignSelf: 'center',
}
});
//config/styles (styling code)
import { Platform } from 'react-native';
import colors from './colors';
export default {
colors,
text: {
color: colors.dark,
fontSize: 18,
fontFamily: Platform.OS === "android" ? "Roboto" : "Avenir",
},
}
//AppFormField (for forms)
import React from 'react';
import { StyleSheet } from 'react-native';
import { useFormikContext } from 'formik';
import AppTextInput from '../AppTextInput';
import ErrorMessage from './ErrorMessage';
export default function AppFormField({ name, ...otherProps }) {
const { errors, handleChange, setFieldTouched, touched } = useFormikContext();
return (
<>
<AppTextInput
onBlur={() => setFieldTouched(name)}
onChangeText={handleChange(name)}
{...otherProps}
/>
<ErrorMessage error={errors[name]} visible={touched[name]} />
</>
);
}
//ListingEditScreen (this the main window to user)
export default function ListingEditScreen() {
return (
<Screen style={styles.container}>
<Form
initialValues={{
title: "",
price: "",
description: "",
category: null,
}}
onSubmit={(values) => console.log(values)}
validationSchema={validationSchema}
>
<AppFormField maxLength={255} name="title" placeholder="Title" />
<AppFormField
keyboardType="numeric"
maxLength={8}
name="price"
placeholder="Price"
width={120}
/>
<Picker
items={categories}
name="category"
numberOfColumns={3}
PickerItemComponent={CategoryPickerItem}
placeholder="Category"
width="50%"
/>
<AppFormField
maxLength={255}
multiline
name="description"
numberOfLines={3}
placeholder="Description"
/>
<SubmitButton title="Post" />
</Form>
</Screen>
);
}
const styles = StyleSheet.create({
container: {
padding: 10,
},
});
but my problem is that the input field only gets acitvated when I touch the placeholder text and not any other part of the text input field!
My main problem
So how can I solve this problem so that I can touch any part of the input field and it gets activated!
Thank-you!
I am building a react-native app with expo, I have only 2 components, WelcomeScreen and PhoneLoginScreen. I am trying to implement firebase phone authentication which works fine on the Web but on iOS Simulator I get an error Verifier._reset is not a function. (In 'verifier._reset()', 'verifiier._reset' is undefined and on Android, it just crashes when I click the continue button that navigates to the PhoneLoginScreen component. Codes below:
App.js
import React from "react"
import { NavigationContainer } from "#react-navigation/native"
import { createNativeStackNavigator } from "#react-navigation/native-stack"
import WelcomeScreen from "./components/WelcomeScreen"
import PhoneLoginScreen from "./components/auth/PhoneLoginScreen"
const Stack = createNativeStackNavigator()
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Welcome">
<Stack.Screen
name="Welcome"
component={WelcomeScreen}
options={{ headerShown: false }}
/>
<Stack.Screen
name="PhoneLogin"
component={PhoneLoginScreen}
options={{ headerShown: false }}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
WelcomeScreen.js
import React from "react"
import { Text, View, Button } from "react-native"
export default function WelcomeScreen({ navigation }) {
return (
<View
style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Welcome</Text>
<Button
title="Continue"
onPress={() => navigation.navigate("PhoneLogin")}
/>
</View>
)
}
PhoneLoginScreen.js
import React, { useRef, useState } from "react"
import { firebaseApp, auth } from "../../firebase"
import {
Text,
View,
TextInput,
Button,
StyleSheet,
TouchableOpacity,
} from "react-native"
import {
FirebaseRecaptchaVerifierModal,
FirebaseRecaptchaBanner,
} from "expo-firebase-recaptcha"
import { PhoneAuthProvider, signInWithCredential } from "firebase/auth"
export default function PhoneLoginScreen() {
const recaptchaVerifier = useRef(null)
const [message, showMessage] = useState()
const [phoneNumber, setPhoneNumber] = useState()
const [verificationId, setVerificationId] = useState()
const [verificationCode, setVerificationCode] = useState()
const firebaseConfig = firebaseApp ? firebaseApp.options : undefined
const attemptInvisibleVerification = true
return (
<View style={styles.center}>
<FirebaseRecaptchaVerifierModal
ref={recaptchaVerifier}
firebaseConfig={firebaseConfig}
attemptInvisibleVerification={attemptInvisibleVerification}
/>
<Text style={{ marginTop: 20 }}>Enter phone number</Text>
<TextInput
style={{ marginVertical: 10, fontSize: 17 }}
placeholder="+1 999 999 9999"
autoFocus
autoCompleteType="tel"
keyboardType="phone-pad"
textContentType="telephoneNumber"
onChangeText={phoneNumber => setPhoneNumber(phoneNumber)}
/>
<Button
title="Send Verification Code"
disabled={!phoneNumber}
onPress={async () => {
try {
const phoneProvider = new PhoneAuthProvider(auth)
const verificationId =
await phoneProvider.verifyPhoneNumber(
phoneNumber,
recaptchaVerifier.current
)
setVerificationId(verificationId)
showMessage({
text: "Verification code has been sent to your phone.",
})
} catch (err) {
showMessage({
text: `Error 111: ${err.message}`,
color: "red",
})
}
}}
/>
<Text style={{ marginTop: 20 }}>Enter Verification code</Text>
<TextInput
style={{ marginVertical: 10, fontSize: 17 }}
editable={!!verificationId}
placeholder="123456"
onChangeText={setVerificationCode}
/>
<Button
title="Confirm Verification Code"
disabled={!verificationId}
onPress={async () => {
try {
const credential = PhoneAuthProvider.credential(
verificationId,
verificationCode
)
await signInWithCredential(auth, credential)
showMessage({
text: "Phone authentication successful 👍",
})
} catch (err) {
showMessage({
text: `Error: ${err.message}`,
color: "red",
})
}
}}
/>
{message ? (
<TouchableOpacity
style={[
StyleSheet.absoluteFill,
{
backgroundColor: 0xffffffee,
justifyContent: "center",
},
]}
onPress={() => showMessage(undefined)}>
<Text
style={{
color: message.color || "blue",
fontSize: 17,
textAlign: "center",
margin: 20,
}}>
{message.text}
</Text>
</TouchableOpacity>
) : undefined}
{attemptInvisibleVerification && <FirebaseRecaptchaBanner />}
</View>
)
}
const styles = StyleSheet.create({
center: {
flex: 1,
justifyContent: "center",
alignItems: "center",
},
})
firebase.js
import firebase from "firebase/compat/app"
import "firebase/compat/auth"
import "firebase/compat/firestore"
// Initialize Firebase
const firebaseConfig = {
// Config info...
}
let firebaseApp
if (firebase.apps.length === 0) {
firebaseApp = firebase.initializeApp(firebaseConfig)
} else {
firebaseApp = firebase.app()
}
const auth = firebase.auth()
export { auth, firebaseApp }
package.json dependencies
"dependencies": {
"#react-navigation/native": "^6.0.6",
"#react-navigation/native-stack": "^6.2.5",
"expo": "~43.0.2",
"expo-firebase-recaptcha": "~2.0.2",
"expo-status-bar": "~1.1.0",
"firebase": "^9.5.0",
"react": "17.0.1",
"react-dom": "17.0.1",
"react-native": "0.64.3",
"react-native-safe-area-context": "3.3.2",
"react-native-screens": "~3.8.0",
"react-native-web": "0.17.1",
"react-native-webview": "11.13.0"
}
I have googled forever and nothing works. Please advice
This is a bug. The maintainers of "expo-firebase-recaptcha" have yet to publish a fix, so until that day comes, this is how you fix it yourself:
Go to node_modules/expo-firebase-recaptcha, open the build folder and find FirebaseRecaptchaVerifierModal.js.
Inside of FirebaseRecaptchaVerifierModal, add the following function to the component definition:
_reset = () => {}
I've included a snippet of the file after adding the empty function definition:
FirebaseRecaptchaVerifierModal.js
[...]
else {
this.setState({
visible: true,
visibleLoaded: false,
resolve,
reject,
});
}
});
}
/**
* Add the following line anywhere inside of the FirebaseRecaptchaVerifierModal component.
*/
_reset = () => {}
onVisibleLoad = () => {
this.setState({
visibleLoaded: true,
});
};
[...]
Note: You will have to do this after every yarn/npm installl or change in node_modules until the publishers push an update.
Error: verifier._reset is not a function. when trying to Sign in with phone using firebase, react native and Expo
FIX FOR EXPO 45, 46
After Surfing through the internet for answers, i failed and din't find anything to make it work on Expo 45 and Expo 46, finally took it to my hands because We can't ship an app with manual recaptcha as it is very bad UX. So after trying every possible prop in the FirebaseRecaptchaVerifierModal, I FINALLY FOUND THE WORKING FIX
By Combining all the fixes and adding one of my own found, I finally can rest in peace as this is now working.
// Declare the Timeout for Initial Page Load Fix
const [isInit, setisInit] = useState(false)
useEffect(() => {
setTimeout(function () {
setisInit(true)
}, 1000)
return () => {
setisInit(false)
}
}, [])
return(
<View>
...
{isInit && (
<FirebaseRecaptchaVerifierModal
ref={recaptchaVerifier}
firebaseConfig={app.options}
androidHardwareAccelerationDisabled={true}
androidLayerType="software"
attemptInvisibleVerification
/>
)}
...
<FirebaseRecaptchaBanner />
</View>
This was the magical line
androidLayerType="software"
I Hope Expo Updates there Documentation and avoid this painful experience for all of us Developers, I mean I literally never have seen an app with manual Recaptcha until im spamming
FirebaseRecaptchaVerifierModal attemptInvisibleVerification Crashes on Android Emulator look at this. This is help me so well.
I add :
<FirebaseRecaptchaVerifierModal ref={recaptchaVerifierRef}
firebaseConfig={firebaseConfig} androidHardwareAccelerationDisabled
attemptInvisibleVerification />
This line on my FirebaseRecaptchaVerifierModal this gonna help to my to problem.
I'm using Picker component of Native-Base for my react-native application. On IOS everything is ok, whereas, on Android side I can not trigger function I added on onValueChange.
Is there anyone faced this issue before?
How did you fix it? I stuck here almost a day.
Here is my code.
<Picker style={{ width: 200, height: 40}}
iosHeader="Branch"
Header="Branch"
mode="dropdown"
textStyle={{color: 'white'}}
placeholder="Branch"
headerBackButtonText="Geri"
selectedValue={this.state.selectedBranch}
onValueChange={(value)=>this.onBranchSelected(value)}
>
{this.state.branches.map((branches, i)=>{
return(
<Picker.Item label={branches.address_line} value={branches.id} key={i}/>
);
}
)}
</Picker>
It does not call the function onBranchSelected on Android.
I tried your code and was working fine for me.
Pasting my code
import React, { Component } from "react";
import { Platform } from "react-native";
import { Container, Header, Title, Content, Button, Icon, Text, Right, Body, Left, Picker, Form } from "native-base";
export default class PickerExample extends Component {
constructor(props) {
super(props);
this.state = {
branches: [
{ address_line: 'address 1', id: 1 },
{ address_line: 'address 2', id: 2 },
{ address_line: 'address 3', id: 3 },
{ address_line: 'address 4', id: 4 },
{ address_line: 'address 5', id: 5 }],
selected1: 1
};
}
onBranchSelected(value) {
this.setState({
selectedBranch: value
});
}
render() {
return (
<Container>
<Header>
<Left>
<Button transparent>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Picker</Title>
</Body>
<Right />
</Header>
<Content>
<Form>
<Picker
style={{ width: 200, height: 40 }}
iosHeader="Branch"
Header="Branch"
mode="dropdown"
textStyle={{ color: 'grey' }}
placeholder='Select branch'
headerBackButtonText='Geri'
selectedValue={this.state.selectedBranch}
onValueChange={(value) => this.onBranchSelected(value)}
>
{this.state.branches.map((branches, i) => {
return (
<Picker.Item label={branches.address_line} value={branches.id} key={i} />
);
}
)}
</Picker>
</Form>
</Content>
</Container>
);
}
}
Dependencies
"native-base": "2.3.5",
"react": "16.0.0",
"react-native": "0.50.0",
This is known issue with Picker. The issue is trying to use .map. I myself couldn't ever get map to work with Picker. The only thing I could find was an npm package called react-native-smart-picker which I was able to use a .map with. There are limitations.
And FYI I also tried other bootstrap frameworks and this is an issue with vanilla react-native.
Heres the link..
https://www.npmjs.com/package/react-native-smart-picker
Heres my github repo...
https://github.com/GavinThomas1192/motoMechanicMeeKanic/blob/master/App/Components/vehicleMakePicker.js
Heres my code where I implemented it.
<ScrollView>
<View style={{ flex: 1, marginTop: 20 }}>
{this.state.makes.length > 1 ?
<ScrollView>
<SmartPicker
expanded={this.state.expanded}
selectedValue={this.state.selectedMake}
label='Select Make'
onValueChange={this.handleChange.bind(this)}>
{
this.state.makes.map((ele) => {
return (<Picker.Item label={ele} value={ele}/>);
})
}
<Picker.Item label='Select Make' value='Toyota'/>
</SmartPicker>
<Button block onPress={() => this.props.vehicleMake(this.state.selectedMake)}>
<Text>Done</Text>
</Button>
</ScrollView> : <Spinner/>
}
</View>
</ScrollView>
Update to show how I handled no expandable button
<Content>
<Text>Vehicle Stats:</Text>
<Text>Year: {this.state.vehicleYear}</Text>
<Text>Make: {this.state.vehicleMake}</Text>
<Text>Model: {this.state.vehicleModel}</Text>
{this.state.vehicleYear === "" ? <VehicleYearPicker vehicleYear={this.yearPicked}/> : undefined}
{this.state.vehicleYear !== "" && this.state.vehicleMake === "" ?
<VehicleMakePicker pickedYear={this.state.vehicleYear} vehicleMake={this.makePicked}/> : undefined}
{this.state.vehicleModel === "" && this.state.vehicleMake !== "" ?
<VehicleModelPicker homeState={this.state} vehicleModel={this.modelPicked}/> : undefined}
</Content>
I followed the facebook documentation on how to generate signed apk exactly. But still I am getting error: undefined is not an object (evaluating 'e.length'
Here is the screenshot
However, the app works fine in Android Emulator with command react-native run-android.
But, I got the issue which was causing the app to crash. It was native-base.
Here is the following code in my App.js:
import React, { Component } from 'react';
import {Text} from 'react-native';
import { Container, Header, Content, Form,Text, Item, Input, Label, Button }
from 'native-base';
export default class ReactNativeExample extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: ''
};
this.doSignIn = this.doSignIn.bind(this);
}
doSignIn() {
let formdata = new FormData();
formdata.append("username", this.state.username)
formdata.append("password", this.state.password)
fetch('http://someweb.com/loginUser',{
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
}).then((response) => response.json())
.then((responseData) => {
console.log("Inside responsejson");
if(responseData.error != true) {
console.log('You have logged in...');
}
}).done();
}
render() {
return (
<Container>
<Header />
<Content>
<Form>
<Item floatingLabel style={{margin: 8}}>
<Label>Username</Label>
<Input ref="username" onChangeText={(username) =>
this.setState({username})}/>
</Item>
<Item floatingLabel last style={{margin: 8}}>
<Label>Password</Label>
<Input ref="username" onChangeText={(password) =>
this.setState({password})}/>
</Item>
<Button block info style={{margin: 8}} onPress={this.doSignIn}>
<Text>Login</Text>
</Button>
</Form>
</Content>
</Container>
<Text> Hello </Text>
);
}
}
I want to know what is wrong with the above native-base code that is making the App crash? Is there any way I can make native-base code work?
Thank You.
ReactNative version: 0.50.1
That's because there is import duplicates of Text component
import { Text } from 'react-native';
import { Container, Header, Content, Form,Text, Item, Input, Label, Button }
from 'native-base';
You can import both Text components via as like this
import { Text as NativeText } from 'react-native';
And then use NativeText. Otherwise, do not duplicate your imports.
tried your code. Was able to generate an apk successfully. Didn't find any issue while running the apk. Posting the code.
import React, { Component } from "react";
import { Container, Header, Content, Form, Text, Item, Input, Label,Button } from "native-base";
export default class ReactNativeExample extends Component {
constructor(props) {
super(props);
this.state = {
username: "",
password: "",
};
this.doSignIn = this.doSignIn.bind(this);
}
doSignIn() {
let formdata = new FormData();
formdata.append("username", this.state.username);
formdata.append("password", this.state.password);
fetch("https://httpbin.org/", {
method: "post",
headers: {
"Content-Type": "multipart/form-data",
},
body: formdata,
})
.then(response => console.log("response", response))
.done();
}
render() {
return (
<Container>
<Header />
<Content>
<Form>
<Item floatingLabel style={{ margin: 8 }}>
<Label>Username</Label>
<Input ref="username" onChangeText={username => this.setState({ username })} />
</Item>
<Item floatingLabel last style={{ margin: 8 }}>
<Label>Password</Label>
<Input ref="username" onChangeText={password => this.setState({ password })} />
</Item>
<Button block info style={{ margin: 8 }} onPress={this.doSignIn}>
<Text>Login</Text>
</Button>
</Form>
</Content>
</Container>
);}
}
When using NativeBase components use <Text/> from 'native-base'
When i click on the select a photo button, Take a photo and select from gallery options pop up. But when i click at those options nothing happens. I am working on windows right now. I tried the same code in mac, selecting the option simply took me to the home screen. Please help.
import React, { Component } from 'react';
import {AppRegistry,View,Text,Image, StyleSheet,PixelRatio,TouchableOpacity } from 'react-native';
import {
Container,
List,
ListItem,
Content,
Footer,
FooterTab,
Header,
Button,
Icon,
Tabs,
Title,
InputGroup,
Input
} from 'native-base';
import{
Actions,
Scene,
Router
}from 'react-native-router-flux';
import ImagePicker from 'react-native-image-picker';
import Reg from './Reg'
export default class Log extends Component{
state = {
avatarSource: null,
};
selectPhotoTapped() {
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
storageOptions: {
skipBackup: true
}
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
let source = { uri: response.uri };
this.setState({
avatarSource: source
});
}
});
}
render(){
return(
<Container>
<View style={styles.container}>
<TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
<View style={[styles.avatar, styles.avatarContainer, {marginBottom: 20}]}>
{ this.state.avatarSource === null ? <Text>Select a Photo</Text> :
<Image style={styles.avatar} source={this.state.avatarSource} />
}
</View>
</TouchableOpacity>
</View>
<Content style={{flex:1, marginTop:80}}>
<List>
<ListItem>
<InputGroup>
<Icon name='ios-at-outline' style={{color:'#5bc0de'}}/>
<Input placeholder="Email" />
</InputGroup>
</ListItem>
<ListItem>
<InputGroup>
<Icon name='ios-lock-outline' style={{color:'#5bc0de'}}/>
<Input placeholder="Password" secureTextEntry />
</InputGroup>
</ListItem>
<View style={{marginTop:10}}>
<Button info style={{alignSelf:'center'}} onPress={Actions.userprofile}>
LOGIN
</Button>
</View>
</List>
</Content>
</Container>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop:50,
justifyContent: 'center',
alignItems: 'center',
},
avatarContainer: {
height:100,
width:100,
borderColor: '#9B9B9B',
borderWidth: 1 / PixelRatio.get(),
justifyContent: 'center',
alignItems: 'center'
},
avatar: {
borderRadius: 75,
width: 150,
height: 150
}
});
Add two permission in AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>