I get navigation error when I switch login screen to Chat - react-native

I have imported and declared const navigation = useNavigation() and navigated to chat with navigation.navigate(Chat) but when I run the VM it gives error and navigationenter image description here
import React , {useState } from 'react';
import {View, StyleSheet,Text ,TouchableOpacity,TextInput} from 'react-native';
import { useNavigation } from '#react-navigation/native';
import { firebase } from '../config/firebaseSDK';
import Signup from '../Screens/SignUp';
import Chat from '../Components/Chat';
const Login = () => {
const navigation = useNavigation()
const [email,setEmail] = useState(' ')
const [password,setPassword] = useState(' ')
const loginUser = async(email,password) =>{
try {
await firebase.auth().signInWithEmailAndPassword(email,password)
.then(()=>navigation.navigate(Chat))
} catch (error){
alert(error.message)
}
}
return (
<View style={styles.container}>
{/* <Text style={{fontWeight:'bold',fontSize:26}}>Login</Text> */}
<View style={{marginTop:40}}>
<TextInput
style={styles.textInput}
placeholder="Email"
onChangeText={(email)=>setEmail(email)}
autoCapitalize="none"
autoCorrect={false}
/>
<TextInput
style={styles.textInput}
placeholder="Password"
onChangeText={(password)=>setPassword(password)}
autoCapitalize="none"
autoCorrect={false}
/>
</View>
<TouchableOpacity
onPress={()=>loginUser(email,password)}
style={styles.button}>
<Text style={{fontWeight:"bold",fontSize:21}}>Login</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={()=>navigation.navigate(Signup)}
style={{marginTop:20}}>
<Text style={{fontWeight:"bold",fontSize:16}}>
Don't have an accout?Registry Now
</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container : {
flex:1,
alignItems:'center',
marginTop:100,
},
textInput:{
paddingTop:20,
paddingBottom:10,
width:400,
fontSize:20,
borderBottomWidth:1,
borderBottomColor:'#000',
marginBottom:10,
textAlign:'center'
},
button :{
marginTop:50,
height:70,
width:250,
backgroundColor:'#026efd',
alignItems:'center',
justifyContent:'center',
borderRadius:50
}
})
export default Login;
This is the error message when I click the login button: The 'navigation' object hasn't been initialized yet. This might happen if you don't have a navigator mounted, or
if the navigator hasn't finished mounting. See https://reactnavigation.org/docs/navigating-without-navigation-prop#handling-initialization for more details.

Related

Stripe payment trigger All modals to open

When i put credits and make a payment the payment is succesfull but for some reason after the payment stripe is triggering all modals to open(from header), like it setting true all the modals , anyone know why ? ( The modal is from another compoenent name "Header" its working fine with everything else in my app .
Code below :
Merry Christmas :)
//React imports
import React, { useState } from 'react';
import { StyleSheet, View, Text, Pressable, Alert, Image , KeyboardAvoidingView , Dimensions , Platform} from 'react-native';
import { useNavigation , useFocusEffect } from '#react-navigation/native';
//Icon imports
import { AntDesign } from '#expo/vector-icons';
import { FontAwesome5 } from '#expo/vector-icons';
//API imports
import axios from 'axios';
import { StripeProvider, CardField, CardFieldInput, createToken, confirmPayment } from '#stripe/stripe-react-native';
import { Buffer } from "buffer";
//useConfirmPayment,useStripe
//My imports
import Header from './Header';
//.Env imports
import {URL} from '#env';
export default function Payment({route}) {
//Constructors for Card Details
const [card, setCard] = useState(CardFieldInput.Details | null);
//Use of navigate Hook
const navigation = useNavigation();
//My local variables
const bookItem = route.params.paramKey;
const bookID = bookItem.id;
const bookPrice = bookItem.Price;
const bookImage = bookItem.image;
//Payment function
const pay = async () => {
//First we create token for the payment
const resToken = await createToken({...card,type:'Card'})
//Then we create data for the payment , like amount and currency
const payData = {
amount : bookPrice * 100,
currency : "eur",
}
console.log(payData)
//If credit card fields are correct fil out ,then continue to further confirmations
if(Object.keys(resToken) == "token"){
//Request to check the success of the payment
await axios.post(URL+"/createPayment",
{...payData}).then((response)=>{
const { confirmPaymentIntent } = confirmPayment(response.data.paymentIntent,{paymentMethodType : 'Card'})
//If confirm is true then update the book table in Bought Column
if(Object.keys(response.data).length > 1){
Alert.alert("Success payment")
//Request to inform the table that this book is bought
axios.post( URL+"/bookBuy",
{
bookCheckID : bookID,
userBoughtItID : global.id
}).catch((error)=>{
console.log("Axios request failed to buy the book")
})
//End of second Axios request
}
else
{
console.log("Token Error ,maybe card credits is wrong")
Alert.alert("Error in payment,maybe card credits are wrong?")
}
}).catch((error)=>{
console.log("Axios request for payment failed")
})
//End of first Axios request
}
else{
Alert.alert("Card credentials are not Valid")
}
}
return (
//Stripe public key provider
<StripeProvider
publishableKey = "pk_test_51MAWjfI5vsjFWvGhrr5n2mAujexURegEgW4ujlSPpois9Em7FBzHrEkuv5zkeRjck8CeLBAcI761eVqgWQ3mL6EX00oSp0WeB6"
merchantIdentifier = "merchant.com.{{E-LIBRARY}}"
urlScheme = "your-url-scheme"
>
<KeyboardAvoidingView
style={{ height: Platform.OS ==='ios' ? Dimensions.get('window').height * 1 : Dimensions.get('window').height * 1}}
behavior={(Platform.OS === 'ios') ? 'position' : "position"}
enabled
keyboardVerticalOffset={Platform.select({ ios: -50, android: -50 })}
>
<View style = {styles.container}>
{/* Header */}
<Header />
{/* Container */}
<View style={styles.container}>
<View style = {styles.viewContainerForInfos}>
<Text style = {styles.bookText}>{bookItem.title}</Text>
<View style = {styles.imageView}>
<Image
style = {{width:'30%',height:'60%',borderRadius:22,position:'relative',resizeMode:'contain'}}
source = {{uri :'data:image/png;base64,' + Buffer.from(bookImage.data,'hex').toString('base64')}}
/>
<AntDesign name="checkcircleo" size={24} color="white" style = {{}} />
</View>
</View>
<View style = {styles.viewForCardinfo}>
<Text style = {styles.creditText}>Credit Card Informations</Text>
<FontAwesome5 name="id-card-alt" size={30} color="black" />
</View>
<View style = {{alignItems:'center',width:'100%',height:'100%'}}>
{/* Card component from Stripe */}
<CardField
postalCodeEnabled={true}
placeholder={{
number: '4242 4242 4242 4242',
}}
cardStyle={{
backgroundColor: '#FFFFFF',
textColor: '#000000',
borderWidth:2,
borderRadius:15
}}
style={{
width: '80%',
height: '8%',
marginVertical: '15%',
}}
onCardChange={(cardDetails) => {
setCard(cardDetails);
}}
/>
{/* Pressable in order for the client to pay */}
<Pressable style = {styles.pressable} onPress = {() => {pay()}}>
<Text style = {styles.pressableText}>Buy</Text>
</Pressable>
</View>
</View>
</View>
</KeyboardAvoidingView>
</StripeProvider>
)
}
Header
//React imports
import React, { useState } from 'react';
import { StyleSheet, Text, View, Pressable, Modal, Platform} from 'react-native';
import { useNavigation } from '#react-navigation/native';
//Icon Imports
import { SimpleLineIcons } from '#expo/vector-icons';
//Icons inside header modal
import { AntDesign } from '#expo/vector-icons';
import { Feather } from '#expo/vector-icons';
export default function Header() {
//Use of navigation Hook
const navigation = useNavigation();
//Modal Constructor
const [modalVisible,setModalVisible] = useState(false);
return (
<View style = {styles.Container}>
{/* Modal*/}
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
setModalVisible(!modalVisible);
}}>
<View style = {styles.modalStyle}>
{/* Pressable and Text for each functionality */}
<Pressable style = {styles.pressable} onPress = { () => navigation.navigate('Home')}>
<AntDesign name="home" size={24} color="black" style = {{marginRight:'2%',marginLeft:'2%'}}/>
<Text style = {styles. textInsideModalPressables}>Home</Text>
</Pressable>
<Pressable style = {styles.pressable} onPress = { () => navigation.navigate('MyBooks')}>
<Feather name="book" size={24} color="black" style = {{marginRight:'2%',marginLeft:'2%'}}/>
<Text style = {styles. textInsideModalPressables}>My Collection</Text>
</Pressable>
<Pressable style = {styles.pressable} onPress = { () => navigation.navigate('Profile')}>
<AntDesign name="profile" size={24} color="black" style = {{marginRight:'2%',marginLeft:'2%'}}/>
<Text style = {styles. textInsideModalPressables}>Profile</Text>
</Pressable>
<Pressable style = {styles.pressable} onPress = { () => navigation.navigate('Settings')}>
<Feather name="settings" size={24} color="black" style = {{marginRight:'2%',marginLeft:'2%'}}/>
<Text style = {styles. textInsideModalPressables}>Settings</Text>
</Pressable>
<Pressable style = {styles.pressable} onPress = { () => navigation.navigate('LogInPage')}>
<AntDesign name="logout" size={24} color="black" style = {{marginRight:'2%',marginLeft:'2%'}}/>
<Text style = {styles. textInsideModalPressables}>Log Out</Text>
</Pressable>
<Pressable onPress={ () => {setModalVisible(!modalVisible)}} style = {styles.pressable}>
<AntDesign name="closecircleo" size={24} color="black" style = {{marginRight:'2%',marginLeft:'2%'}}/>
<Text style = {styles. textInsideModalPressables}>Close modal</Text>
</Pressable>
</View>
</Modal>
{/* Pressable Mechanism in order to open the Modal */}
<Pressable onPress={ () => {setModalVisible(!modalVisible)}} style = {styles.pressableMenu}>
<SimpleLineIcons style = {styles.iconMenu} name="menu" size={24} color="white" />
<Text style = {styles.menuText}>Menu</Text>
</Pressable>
<View style ={{width:'50%',alignItems:'center',justifyContent:'center'}}>
<Text style = {styles.nameText}> E-Library</Text>
</View>
</View>
);}

Recat Native / got an invalid value for 'component' prop for the screen

I'm korean. and Im not good at english. please understand about this.
i want if i push the button, move the page.
but
got an invalid value for 'component' prop for the screen
this error keep appear in StyleScreen.
I'm defintly beginner, so if you upload full code, I'm so appreciate that.
this is my App.js code:
import * as React from 'react';
import { useState } from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import MainScreen from './MainScreen';
import DetailScreen from './DetailScreen';
import StyleScreen from './StyleScreen';
const Stack = createStackNavigator();
const App = () => {
const [overlay, setOverlay] = useState(false);
const toggleOverlay = () => {
setOverlay(!overlay);
}
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="MAIN">
<Stack.Screen name="MAIN" component={MainScreen}
options={{
title: '예산'
}}/>
<Stack.Screen name="DETAIL" component={DetailScreen}
options={{
title: '색'
}}/>
<Stack.Screen name="STYLE" component={StyleScreen}
options={{
title: '스타일'
}}/>
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;
this is StyleScreen.js :
import React, { Component } from 'react';
import { useState } from 'react';
import { StatusBar } from 'expo-status-bar';
import { Button, StyleSheet, Text, Dimensions, View, ScrollView, Image, navigation } from 'react-native';
let natural = require('./내추럴.png');
let modern = require('./모던.jpg');
let romantic = require('./로맨틱.jpg');
let NEurope = require('./북유럽.png');
let junk = require('./정크4.jpg');
let minimal = require('./미니멀.jpg');
const HomeScreen=({navigation}) => {
return (
<View style={styles.container}>
<StatusBar style="block"></StatusBar>
<View style={styles.ask1}>
<Text style={styles.askcolor}>선호하는 스타일을</Text>
<Text style={styles.askcolor}>선택해주세요</Text>
</View>
<View style={styles.day2}>
<View style={styles.day}>
<Image style={styles.image} source={modern}/>
<Image style={styles.image2} source={NEurope}/>
</View>
<View style={styles.day}>
<Text style={styles.colorname}> 모던</Text>
<Text style={styles.colorname}> 북유럽</Text>
</View>
<View style={styles.day}>
<Image style={styles.image} source={minimal}/>
<Image style={styles.image2} source={natural}/>
</View>
<View style={styles.day}>
<Text style={styles.colorname}> 미니멀</Text>
<Text style={styles.colorname}> 내추럴</Text>
</View>
<View style={styles.day}>
<Image style={styles.image} source={romantic}/>
<Image style={styles.image2} source={junk}/>
</View>
<View style={styles.day}>
<Text style={styles.colorname}> 로맨틱</Text>
<Text style={styles.colorname}> 정크</Text>
</View>
</View>
<View style={styles.button}>
<Button onPress={() => navigation.navigate('DETAIL')} title='다음으로'/>
</View>
</View>
);
}
const styles = StyleSheet.create({
container:{
flex:1,
backgroundColor:"white"
},
ask1:{
flex:0.3,
justifyContent:"center",
marginTop:70,
marginBottom:40,
},
askcolor:{
fontSize:34,
fontWeight:"900",
paddingHorizontal:30,
},
image:{
height: 130,
width: 158,
borderRadius:10,
backgroundColor:"black"
},
image2:{
height: 130,
width: 158 ,
borderRadius:10,
marginLeft:28,
},
day:{
flexDirection: 'row',
},
day2:{
flex:3,
paddingHorizontal:30,
},
colorname:{
fontSize:17,
fontWeight:"300",
paddingHorizontal:23,
paddingVertical:13,
},
button:{
flex:0.43,
marginLeft:286,
}
})
i think you have not exported your styleScreen component, that might be the issue here and also your "StyleScreen" component is named "HomeScreen" so I would suggest rename is properly and export it by default.
In StyleScreen component, you have imported "navigation" from "react-native" which I think is not correct.
You didn't export StyleScreen component.
Add this at bottom line of your StyleScreen.js.
export default StyleScreen;
try to replace code
const HomeScreen=({navigation}) => {
with
export default StyleScreen =({navigation}) => {

Can not show Toast with Galio-Framework

I'm init a test app whith expo-cli.
Install galio-framework
And put one of Toast in screens.But not show anything.
Is my code wrong?
this is my code in App.js
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View,Button } from 'react-native';
import {Toast,Block} from 'galio-framework';
export default function App() {
let isShow= true;
const { useNativeDriver } = this.props;
// const [isShow, setShow] = useState(false);
const setShow = (v)=>{
console.log("show change "+v);
isShow= v;
}
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<StatusBar style="auto" />
<Button shadowless onPress={() => setShow(!isShow)} style={styles.btnCC}>click here for toast notifications</Button>
<Block style={styles.bl}>
<Toast isShow={true} positionIndicator="top">This is a top positioned toast</Toast>
<Toast isShow={isShow} positionIndicator="center" color="success">This is a center positioned toast</Toast>
</Block>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
bl:{
flex: 1,
height:200,
width:100,
// alignItems: 'center',
// justifyContent: 'center',
},
btnCC:{
width:200,
backgroundColor: '#006600',
}
});
Is my code wrong?Or is the framework bug?
isShow variable must be React state. Change code like this
export default function App() {
const [isShow, setShow] = React.useState(false)
const { useNativeDriver } = this.props;
return (
<View style={styles.container}>
<Text>Open up App.js to start working on your app!</Text>
<StatusBar style="auto" />
<Button shadowless onPress={() => setShow(!isShow)} style={styles.btnCC}>click here for toast notifications</Button>
<Block style={styles.bl}>
<Toast isShow={true} positionIndicator="top">This is a top positioned toast</Toast>
<Toast isShow={isShow} positionIndicator="center" color="success">This is a center positioned toast</Toast>
</Block>
</View>
);
}

Why can't clear value from TextInput in react native using Hooks?

I am trying to clear user's value from TextInput when user click on button but ican't get it.
I am implementing this demo using Hooks in react-native.
So please help me I am new in hooks with react-native.Thank you in advanced.
import React, { useState, useEffect } from 'react';
import { StyleSheet, View, TextInput, TouchableOpacity, Text } from 'react-native';
import { RFValue } from 'react-native-responsive-fontsize';
import { heightPercentageToDP as hp, widthPercentageToDP as wp } from 'react-native-responsive-screen';
const Login = ({ navigation }) => {
const [name, setName] = useState('');
const [password, setPassword] = useState('');
/* useEffect(() => {
console.log("login screen");
setName('');
setPassword('');
}); */
function resetTextInput () {
console.log("reset TextInput");
setName(" ");
setPassword(" ");
}
return (
<View style={styles.mainContainer}>
<Text style={styles.txtTitle}>Login</Text>
<View style={{ marginTop: 80 }}>
<TextInput
placeholder={'Username'}
style={styles.txtInput}
onChangeText={(name) => { setName(name) }}
/>
<TextInput
placeholder={'Password'}
style={styles.txtInput}
secureTextEntry={true}
onChangeText={(password) => { setPassword(password) }}
/>
</View>
<TouchableOpacity style={styles.loginBtn} onPress={()=>{resetTextInput()}}>
<Text style={styles.loginBtnTxt}>Login</Text>
</TouchableOpacity>
</View>
)
}
You can set a null value:
function resetTextInput () {
console.log("reset TextInput");
setName(null);//changed this
setPassword(null);//changed this
}
and the main thing set the state value using TextInput props "value"
<View style={{ marginTop: 80 }}>
<TextInput
placeholder={'Username'}
style={styles.txtInput}
value={name} // set state to value prop
onChangeText={(name) => { setName(name) }}
/>
<TextInput
placeholder={'Password'}
style={styles.txtInput}
secureTextEntry={true}
value={password} // set state to value prop
onChangeText={(password) => { setPassword(password) }}
/>
</View>
This solution will help you.
User empty quotes when reseting values,
function resetTextInput () {
console.log("reset TextInput");
setName('');//changed this
setPassword('');//changed this
}
and give used respective state in value prop.
<TextInput
placeholder={'Password'}
style={styles.txtInput}
secureTextEntry={true}
onChangeText={(password) => { setPassword(password) }}
value={password}
/>
same for first TextInput,

undefined is not an object (evaluating'_this2.props.navigation.navigate') - React Native

I am having trouble navigating through screens with a simple button.
This is my App.js
export default class App extends Component<Props> {
render() {
return (
<AppStackNavigator/>
);
}
}
const AppStackNavigator = StackNavigator({
Login: { screen: LoginScreen },
Home: { screen: HomeScreen },
},{
navigationOptions: {
gesturesEnabled:false
}
})
Login.js
export default class Login extends Component {
render() {
return(
<SafeAreaView style={styles.container}>
<StatusBar barStyle='light-content'/>
<KeyboardAvoidingView behavior='padding' style={styles.container}>
<TouchableWithoutFeedback style={styles.container} onPress={Keyboard.dismiss}>
<View style={styles.logoContainer}>
<View style={styles.logoContainer}>
<Image style={styles.logo}
source={require('../images/logo/logo.png')}>
</Image>
<Text style={styles.title}>
Sports Chat App
</Text>
</View>
<View style={styles.infoContainer}>
<TextInput style={styles.input}
placeholder="Enter name"
placeholderTextColor='#ffffff'
keyboardType='default'
returnKeyType='next'
autoCorrect={false}
onSubmitEditing={()=> this.refs.phoneNumber.focus()}
/>
<TextInput style={styles.input}
placeholder="Enter phone number"
placeholderTextColor='#ffffff'
keyboardType='phone-pad'
ref={'phoneNumber'}
/>
<TouchableOpacity style={styles.buttonContainer}>
<Button title='LogIn' onPress={()=>this.props.navigation.navigate('Home')}/>
</TouchableOpacity>
</View>
</View>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
};
LoginScreen.js
class LoginScreen extends Component {
render(){
return (
<View>
<Login>
</Login>
</View>
);
}
}
I keep getting the error undefined is not an object (evaluating'_this2.props.navigation.navigate') whenever i try use the Login button in Login.js,
I want this to navigate to the home screen but cant figure out why this keeps happening.
If i try do it without the components it works fine.
Click to View error message
Add a navigation props to Login in LoginScreen.js, Because LoginScreen has props navigation but Login don't.
render(){
return (
<View>
<Login navigation ={this.props.navigation}>
</Login>
</View>
);
}
App.js
import React, { Component } from "react";
import { Text, View } from "react-native";
import AppStackNavigator from "./AppStackNavigator";
export default class App extends Component<Props> {
render() {
return <AppStackNavigator />;
}
}
AppStackNavigator
import React, { Component } from "react";
import { StackNavigator } from "react-navigation";
import { View, Text, TouchableOpacity } from "react-native";
const LoginScreen = props => (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Login navigation={props.navigation} />
</View>
);
const HomeScreen = () => (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<Text>Home</Text>
</View>
);
const Login = props => (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<TouchableOpacity
onPress={() => {
props.navigation.navigate("Home");
}}
>
<Text>GO to home from login</Text>
</TouchableOpacity>
</View>
);
export default (AppStackNavigator = StackNavigator(
{
Login: { screen: LoginScreen },
Home: { screen: HomeScreen }
},
{
headerMode: "none",
navigationOptions: {
gesturesEnabled: false
}
}
));
You need to access the navigation prop in the component. Check the official guide.
reactnavigation Official guide
import React from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';
class MyBackButton extends React.Component {
render() {
return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />;
}
}
// withNavigation returns a component that wraps MyBackButton and passes in the
// navigation prop
export default withNavigation(MyBackButton);