I was trying to navigate cross different screens on button click in React Native. Following is the code:
App.tsx
import React from "react";
import { StyleSheet, View, Text} from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import Login from './src/screens/Login/login'
import SignUp from './src/screens/SignUp/signUp'
import { getItem } from './src/utility/AsyncStorage'
export default function App() {
const [gmailId, setGmailId] = React.useState("");
const [password, setPassword] = React.useState("");
React.useEffect(() => {
getItem("gmailId").then((value:any) => {setGmailId(value)});
getItem("password").then((value:any) => {setPassword(value)});
}, []);
const RootStack = createNativeStackNavigator();
return (
<View style={styles.container}>
<NavigationContainer>
<RootStack.Navigator initialRouteName="Login">
<RootStack.Screen name="Login" component={Login} />
<RootStack.Screen name="signup" component={SignUp} />
</RootStack.Navigator>
</NavigationContainer>
{/* {(!gmailId && !password)? <Login/>: <Text>Logged In</Text>} */}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
}
});
login.tsx
import React from "react";
import { Text, View, Image, TextInput, TouchableOpacity} from 'react-native';
import { SocialIcon } from 'react-native-elements'
import { loginStyle } from './loginStyle'
import { signIn } from './loginLogic'
const Login = (navigation:any) => {
const [gmailId, setGmailId] = React.useState("");
const [password, setPassword] = React.useState("");
const navigateToSignUp = () => {
navigation.navigate('signup')
};
return (
<View style={styles.container}>
<Image
style={styles.tinyLogo}
source={require( "../../../assets/icon.png")}
/>
<View style={{ width: '100%', alignItems: 'center', justifyContent: 'center', marginTop: 30}}>
<TextInput
style={styles.input}
placeholder="Enter Gmail Id"
onChangeText={setGmailId}
/>
<TextInput
style={styles.input}
onChangeText={setPassword}
placeholder="Enter your Password"
secureTextEntry={true}
/>
<TouchableOpacity
style={[styles.button, styles.loginButton]}
onPress={()=>signIn(gmailId, password)}>
<Text style={styles.text}>Login</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.signupButton]}
onPress={() => navigateToSignUp}>
<Text style={styles.text}>Create New Account</Text>
</TouchableOpacity>
</View>
<View style={{flexDirection: 'row', alignItems: 'center', width: '95%', margin: 10, marginTop: 25}}>
<View style={{flex: 1, height: 1, backgroundColor: 'black'}} />
<View>
<Text style={{width: 100, textAlign: 'center'}}>Social Login</Text>
</View>
<View style={{flex: 1, height: 1, backgroundColor: 'black'}} />
</View>
<SocialIcon
style={{width:"85%"}}
title='Sign In With Google'
button
type='google'
onPress={()=>{console.log('Sign In With Google')}}
/>
</View>
)
}
export default Login
//===================== STYLE SECTION =====================
const styles = loginStyle()
SignUp.tsx
import { StyleSheet, Text, View } from 'react-native'
import React from 'react'
const SignUp = () => {
return (
<View>
<Text>signUp</Text>
</View>
)
}
export default SignUp
const styles = StyleSheet.create({})
My coding is not throwing any error yet none of the screens are visible (Not even the initialRoute). On running the code, it shows up a White page only.
Please help me rectify the issue.
import React from "react";
import { Text, View, Image, TextInput, TouchableOpacity} from 'react-native';
import { SocialIcon } from 'react-native-elements'
import { loginStyle } from './loginStyle'
import { signIn } from './loginLogic'
const Login = ({navigation:any}) => {
const [gmailId, setGmailId] = React.useState("");
const [password, setPassword] = React.useState("");
const navigateToSignUp = () => {
navigation.navigate('signup')
};
return (
<View style={styles.container}>
<Image
style={styles.tinyLogo}
source={require( "../../../assets/icon.png")}
/>
<View style={{ width: '100%', alignItems: 'center', justifyContent: 'center', marginTop: 30}}>
<TextInput
style={styles.input}
placeholder="Enter Gmail Id"
onChangeText={setGmailId}
/>
<TextInput
style={styles.input}
onChangeText={setPassword}
placeholder="Enter your Password"
secureTextEntry={true}
/>
<TouchableOpacity
style={[styles.button, styles.loginButton]}
onPress={()=>signIn(gmailId, password)}>
<Text style={styles.text}>Login</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.signupButton]}
onPress={() => navigateToSignUp}>
<Text style={styles.text}>Create New Account</Text>
</TouchableOpacity>
</View>
<View style={{flexDirection: 'row', alignItems: 'center', width: '95%', margin: 10, marginTop: 25}}>
<View style={{flex: 1, height: 1, backgroundColor: 'black'}} />
<View>
<Text style={{width: 100, textAlign: 'center'}}>Social Login</Text>
</View>
<View style={{flex: 1, height: 1, backgroundColor: 'black'}} />
</View>
<SocialIcon
style={{width:"85%"}}
title='Sign In With Google'
button
type='google'
onPress={()=>{console.log('Sign In With Google')}}
/>
</View>
)
}
export default Login
please try it.
or
import React from "react";
import { Text, View, Image, TextInput, TouchableOpacity} from 'react-native';
import { SocialIcon } from 'react-native-elements'
import { loginStyle } from './loginStyle'
import { signIn } from './loginLogic'
const Login = (props:any) => {
const [gmailId, setGmailId] = React.useState("");
const [password, setPassword] = React.useState("");
const navigateToSignUp = () => {
props.navigation.navigate('signup')
};
return (
<View style={styles.container}>
<Image
style={styles.tinyLogo}
source={require( "../../../assets/icon.png")}
/>
<View style={{ width: '100%', alignItems: 'center', justifyContent: 'center', marginTop: 30}}>
<TextInput
style={styles.input}
placeholder="Enter Gmail Id"
onChangeText={setGmailId}
/>
<TextInput
style={styles.input}
onChangeText={setPassword}
placeholder="Enter your Password"
secureTextEntry={true}
/>
<TouchableOpacity
style={[styles.button, styles.loginButton]}
onPress={()=>signIn(gmailId, password)}>
<Text style={styles.text}>Login</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.signupButton]}
onPress={() => navigateToSignUp}>
<Text style={styles.text}>Create New Account</Text>
</TouchableOpacity>
</View>
<View style={{flexDirection: 'row', alignItems: 'center', width: '95%', margin: 10, marginTop: 25}}>
<View style={{flex: 1, height: 1, backgroundColor: 'black'}} />
<View>
<Text style={{width: 100, textAlign: 'center'}}>Social Login</Text>
</View>
<View style={{flex: 1, height: 1, backgroundColor: 'black'}} />
</View>
<SocialIcon
style={{width:"85%"}}
title='Sign In With Google'
button
type='google'
onPress={()=>{console.log('Sign In With Google')}}
/>
</View>
)
}
export default Login
this one surely help you
thanks
Related
whenever i click on textinput , key board appears and disappears, i also tried on other android device as well
import React, { useState } from 'react';
import {SafeAreaView,Image,StyleSheet,FlatList,View,Text,Button,TextInput,StatusBar,ScrollView,TouchableOpacity,Dimensions,}
from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import ForgotScreen from './ForgotScreen';
const {width, height} = Dimensions.get('window');
const Login = ({navigation}) => {
const [email , setEmail]= useState('')
return (
<SafeAreaView style={{flex: 1 , backgroundColor:'white'}}>
<StatusBar backgroundColor={'white'} barStyle="dark-content" />
<View style={{flex:0.5 ,alignItems:'center', justifyContent:'center'}}>
<Text style={{fontWeight:'bold' , color:'black',fontSize:20 ,margin:50}}>Login</Text>
**<TextInput placeholder='Email' placeholderTextColor={'grey'} style={styles.input_text} value={email} onChangeText={setEmail}/>
<TextInput placeholder='Password' placeholderTextColor={'grey'} style={styles.input_text}/>**
<TouchableOpacity style={{justifyContent:'center' , width:'90%' }} onPress={() => navigation.navigate('ForgotScreen')}>
<Text style={{color:'#A2D5AB' , alignSelf:'flex-end',marginVertical:15 , justifyContent:'center'}}>Forgot Password?</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.btn}>
<Text style={{color:'white'}} onPress={() => navigation.navigate('HomeScreen')}>Login</Text>
</TouchableOpacity>
</View>
<View style={{flex:0.5 ,alignItems:'center', justifyContent:'center'}}>
<TouchableOpacity>
<Text style={{color:'#A2D5AB' , alignSelf:'baseline' , justifyContent:'center' , marginTop:200}} onPress={() => navigation.navigate('SignUp')}>Sign up an account</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const styles=StyleSheet.create({
input_text:{
width:'90%',
height:50,
color:'black',
borderRadius:10,
borderBottomWidth:1,
borderColor:'grey',
},
btn: {
width:'90%',
shadowColor:"black",
shadowOpacity:0.8,
elevation:3,
shadowRadius:15,
height: 50,
marginHorizontal:10,
borderRadius: 5,
backgroundColor: 'gold',
justifyContent: 'center',
alignItems: 'center',
},
})
export default Login;
I am new to react and react native technology and I am stuck into a warning which I am not able to solve.
Two warnings I get:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it
indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method in PhoneInput (at Login.js:40)
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it
indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function in CountryPicker.
Here is my Login.js
import React, {useEffect, useState, useRef } from "react";
import {
View, Text,TouchableOpacity,
StyleSheet, Image, SafeAreaView,
TextInput,
StatusBar, ScrollView
} from 'react-native';
import { Card } from "react-native-shadow-cards";
import PhoneInput from 'react-native-phone-number-input';
import Styling from "../components/Styling";
const Login = (props) => {
const phoneInput = useRef(PhoneInput > (null));
const [phoneNumber,setphoneNumber]=useState(null);
return (
<View style={styles.container}>
<StatusBar backgroundColor='#1e3d59' barStyle="light-content" />
<ScrollView>
<View style={styles.header}>
<Image source={require('../assets/images/login.png')}
style={{ height: 150, width: 150, }}></Image>
</View>
<View
style={[styles.footer]}>
<Text style={Styling.text_footer}>Mobile Number</Text>
<View style={{marginTop:10,
alignContent:'center',
alignItems:'center',
paddingLeft:15,
borderWidth:1,
borderColor:'#d7dade',
borderRadius:20,
flexDirection:'row',
height:72,}}>
<SafeAreaView >
<PhoneInput
containerStyle={{
backgroundColor: '#fff',
borderColor:'black',
alignContent:'center',
height:70,
}}
flagButtonStyle={{
width:'15%'
}}
textContainerStyle={{
backgroundColor: '#fff',
}}
ref={phoneInput}
defaultValue={phoneNumber}
defaultCode="IN"
layout="first"
keyboardType='numeric'
onChangeText={setphoneNumber}
></PhoneInput>
</SafeAreaView>
</View>
<TouchableOpacity on onPress={() => props.onSubmit('+91'+phoneNumber)}>
<Card style={[containerStyle={
height:50,
elevation:0,
borderRadius:10,
backgroundColor: '#ff6e40',
width:"100%",
alignItems:'center',
alignContent:'center',
justifyContent:'center'
},{marginTop:30}]}>
<View >
<Text style={[Styling.textSign, {color:'#fff'}]}>Request OTP</Text>
</View>
</Card>
</TouchableOpacity>
</View>
</ScrollView>
</View>
);
};
export default Login;
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection:"column",
backgroundColor: '#1e3d59',
width: '100%',
},
header: {
alignItems: 'center',
height:"50%",
justifyContent:"center"
},
footer: {
backgroundColor: "white",
borderTopLeftRadius: 30,
borderTopRightRadius: 30,
paddingHorizontal: 20,
paddingTop: 20,
paddingBottom:600
},
});
Here is my App.js
import React, { useState } from 'react';
import auth from '#react-native-firebase/auth';
import VerifyCode from './src/screens/VerifyCode';
import AuthStack from './src/navigation/AuthStack';
import Login from './src/auth/Login';
import { NavigationContainer } from '#react-navigation/native';
const App = () => {
const [confirm, setConfirm] = useState(null);
const [authenticated, setAuthenticated] = useState(false);
const signIn = async (phoneNumber)=> {
try {
const confirmation = await auth().signInWithPhoneNumber(phoneNumber);
setConfirm(confirmation);
} catch (error) {
alert(error);
}
}
const confirmVerificationCode= async (code) =>{
try {
await confirm.confirm(code);
setConfirm(null);
} catch (error) {
alert('Invalid code');
}
}
auth().onAuthStateChanged((user) => {
if(user) {
setAuthenticated(true);
} else {
setAuthenticated(false);
}
})
return(
<NavigationContainer>
{ authenticated? (
<AuthStack/>
)
:
confirm? (
<VerifyCode onSubmit={confirmVerificationCode}/>
)
:
<Login onSubmit={signIn}/>
}
</NavigationContainer>
);
}
export default App;
Here is my VerifyCode.js
import React, { useState} from "react";
import {
View, Text,Platform, TouchableOpacity,
StyleSheet, Image,
TextInput,
StatusBar, ScrollView
} from 'react-native';
import { Card } from "react-native-shadow-cards";
import Styling from "../components/Styling";
const Login = (props) => {
const [code, setCode] = useState('');
return (
<View style={styles.container}>
<StatusBar backgroundColor='#1e3d59' barStyle="light-content" />
<ScrollView>
<View style={styles.header}>
<Image source={require('../assets/images/login.png')}
style={{ height: 150, width: 150, }}></Image>
</View>
<View
style={[styles.footer]}>
<View style={{marginTop:10,
alignContent:'center',
alignItems:'center',
alignSelf:'center',
justifyContent:"center",
borderWidth:1,
borderColor:'#d7dade',
borderRadius:20,
height:60,
width:"40%"
}}>
<TextInput
placeholder="Enter OTP"
autoFocus
value={code}
onChangeText={setCode}
keyboardType="numeric"
style={{fontSize:20,}}
></TextInput>
</View>
<View style={{width:"100%", alignSelf:"center"}}>
<TouchableOpacity on onPress={() => props.onSubmit(code)}>
<Card style={[containerStyle={
height:50,
elevation:0,
borderRadius:10,
backgroundColor: '#ff6e40',
alignItems:'center',
alignContent:'center',
justifyContent:'center'
},{marginTop:20}]}>
<View >
<Text style={[Styling.textSign, {color:'#fff'}]}>Confirm</Text>
</View>
</Card>
</TouchableOpacity>
</View></View>
</ScrollView>
</View>
);
};
export default Login;
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection:"column",
backgroundColor: '#1e3d59',
width: '100%',
},
header: {
alignItems: 'center',
justifyContent:"center",
height:"50%"
},
footer: {
backgroundColor: "white",
borderTopLeftRadius: 30,
borderTopRightRadius: 30,
paddingHorizontal: 20,
paddingTop: 20,
paddingBottom:600
},
});
I'm newbie in React-native and I'm confused on how can I pass the parameter to another js file when returning a View, The second problem , The code I used below is when returning home the previous page(login) didn't close or gone and the home didn't view properly. I'm aware using react-nativigation but it's hard for me to implement but is there any other way to direct login when it loads? please need some help for this , here's my code,
Login.js After login from googlesignin when the state loaded it goes to another activity
import { Home } from "../screens"
render() {
return (
<View style={styles.container}>
<GoogleSigninButton
style={{ width: 222, height: 48 }}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
onPress={this.signIn}
/>
{this.state.loaded ?
<View style={{ width: 160, marginTop: 10 }}>
{renderLogin(this)} //return some value
</View>
: <Text>Not signIn</Text>}
</View>
);
}
}
function renderLogin(ts) {
return (
<Home /> // i want to pass value to home js example: 'ts.state.userGoogleInfo.user.photo'
)
}
Whole code in Login.js
import React, { Component } from 'react';
import { View, StyleSheet, ToastAndroid, Button, Text, Image } from "react-native";
import { Home } from "../screens"
import {
GoogleSignin,
GoogleSigninButton,
statusCodes,
} from '#react-native-community/google-signin';
GoogleSignin.configure({
webClientId: '2622122222248-3v21124124124124.apps.googleusercontent.com',
offlineAccess: true, // if you want to access Google API on behalf
});
class Login extends Component {
constructor(props) {
super(props)
this.state = {
userGoogleInfo: {},
loaded: false
}
}
static navigationOptions = {
title: 'Login',
};
signIn = async () => {
try {
console.log("Processing");
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
this.setState({
userGoogleInfo: userInfo,
loaded: true
})
console.log(this.state.userGoogleInfo);
console.log(this.state.userGoogleInfo.user.name)
console.log(this.state.userGoogleInfo.user.email)
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
console.log("e 1");
} else if (error.code === statusCodes.IN_PROGRESS) {
console.log("e 2");
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
console.log("e 3");
} else {
console.log(error.message);
}
}
};
render() {
return (
<View style={styles.container}>
<GoogleSigninButton
style={{ width: 222, height: 48 }}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
onPress={this.signIn}
/>
{this.state.loaded ?
<View style={{ width: 160, marginTop: 10 }}>
{renderLogin(this)}
</View>
: <Text>Not signIn</Text>}
</View>
);
}
}
function renderLogin(ts) {
return (
<Home />
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#000000',
padding: 15,
},
buttons: {
width: 20
}
});
export default Login;
Home.js
import React from 'react';
import {
StyleSheet,
View,
Text,
ScrollView,
FlatList,
TouchableOpacity,
Image,
ImageBackground,
LogBox
} from 'react-native';
import { PriceAlert, TransactionHistory } from "../components"
import { dummyData, COLORS, SIZES, FONTS, icons, images} from '../constants';
const Home = ({ navigation }) => {
const [trending, setTrending] = React.useState(dummyData.trendingCurrencies)
const [transactionHistory, setTransactionHistory] = React.useState(dummyData.transactionHistory)
function renderHeader(){
const renderItem = ({item, index}) =>(
<TouchableOpacity
style={{
width:155,
paddingVertical:SIZES.padding,
paddingHorizontal:SIZES.padding,
marginLeft: index == 0 ? SIZES.padding : 0,
marginRight: SIZES.radius,
borderRadius: 15,
backgroundColor: COLORS.white
}}
onPress={() => navigation.navigate("CryptoDetail", {currency:item})}
>
{/* Currency*/}
<View style={{ flexDirection:'row'}}>
<View>
<Image
source={item.image}
resizeMode="cover"
style={{
marginTop: 5,
width: 25,
height: 25
}}
/>
</View>
<View style={{marginLeft: SIZES.base}}>
<Text style={{...FONTS.h3}}>{item.currency}</Text>
<Text style={{ color:COLORS.gray, ...FONTS.body3 }}></Text>
</View>
</View>
{/* value*/}
{/* <View style={{ marginTop:SIZES.radius}}> */}
{/* <Text style={{...FONTS.h6}}>₱{item.amount}</Text> */}
{/* <Text style={{color: item.type =="I" ? COLORS.green : COLORS.red, ...FONTS.h5}}>₱{item.amount}</Text> */}
{/* </View> */}
</TouchableOpacity>
)
return(
<View
style={{
width: "100%",
height: 210,
...styles.shadow
}}
>
<ImageBackground
source={images.banner}
resizeMode="cover"
style={{
flex: 1,
alignItems:'center'
}}
>
{/* Header Bar */}
<View
style={{
marginTop:SIZES.padding *1,
width: "100%",
alignItems: "flex-end",
paddingHorizontal: SIZES.padding
}}
>
<TouchableOpacity
style={{
width: 20,
height: 20,
alignItems: "center",
justifyContent:"center"
}}
onPress={() => console.log("Notification on pressed")}
>
<Image
source={icons.notification_white}
resizeMode="contain"
style={{flex: 1}}
/>
</TouchableOpacity>
</View>
{/* Balance */}
<View
style={{
alignItems: 'center',
justifyContent:'center'
}}
>
<Text style={{ color: COLORS.white, ...FONTS.h3}}>Available Balance</Text>
<Text style={{ marginTop:SIZES.base, color:COLORS.white, ...FONTS.h2}}>₱{dummyData.portfolio.balance}</Text>
<Text style={{color:COLORS.white, ...FONTS.body5}}>{dummyData.portfolio.changes} Last 24 hours</Text>
</View>
{/* Trending */}
<View
style={{
position:'absolute',
bottom: "-30%"
}}
>
<Text style={{ marginLeft:SIZES.padding,
color: COLORS.white, ...FONTS.h3 }}>Dashboard</Text>
<FlatList
contentContainerStyle={{marginTop:SIZES.base}}
data={trending}
renderItem={renderItem}
keyExtractor={item => `${item.id}`}
horizontal
showsHorizontalScrollIndicator={false}
/>
</View>
</ImageBackground>
</View>
)
}
function renderAlert(){
return (
<PriceAlert/>
)
}
function renderNotice(){
return (
<View
style={{
marginTop:SIZES.padding-6,
marginHorizontal: SIZES.padding,
padding: 12,
borderRadius:SIZES.radius,
backgroundColor:COLORS.secondary,
...styles.shadow
}}
>
<Text style={{color:COLORS.white, ...FONTS.h4}}>Announcement:</Text>
<Text style={{marginTop:SIZES.base, color:COLORS.white, ...FONTS.body4, lineHeight:18}}>We offer you an application to guide and track your data.
Learn how to use this application by reading instructions and guide.
</Text>
<TouchableOpacity
style={{
marginTop:SIZES.base
}}
onPress={()=> console.log("Learn More")}
>
<Text style={{ textDecorationLine: 'underline',
color:COLORS.green, ...FONTS.h4}}>Learn more
</Text>
</TouchableOpacity>
</View>
)
}
function renderTransactionHistory(){
return (
<TransactionHistory
customContainerStyle={{ ...styles.shadow}}
history={transactionHistory}
/>
)
}
return (
<ScrollView>
<View style={{ flex:1, paddingBottom:130 }}>
{renderHeader()}
{renderAlert()}
{renderNotice()}
{renderTransactionHistory()}
</View>
</ScrollView>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
shadow: {
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.30,
shadowRadius: 4.65,
elevation: 8,
}
})
export default Home;
Apps.js
import React from 'react';
import { Transaction, TevDetail, Login } from "./screens";
import { createStackNavigator } from "#react-navigation/stack";
import { NavigationContainer } from '#react-navigation/native';
import SplashScreen from 'react-native-splash-screen';
import Tabs from "./navigation/tabs";
const Stack = createStackNavigator();
const App = () => {
React.useEffect(() => {
SplashScreen.hide()
}, [])
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false
}}
initialRouteName={'Login'}
>
<Stack.Screen
name="Home"
component={Tabs}
/>
<Stack.Screen
name="TevDetail"
component={TevDetail}
/>
<Stack.Screen
name="Transaction"
component={Transaction}
/>
<Stack.Screen
name="Login"
component={Login}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
export default App;
I have am making a form in React Native (testing on IOS/Expo go) and for reasons that I cannot pinpoint, my TouchableWithoutFeedback's onPress event is not firing at all.
I made sure to wrap the TouchableWithoutFeedback's children in a single View component (as suggested by other answers on github and stack overflow), but the problem persists.
import React from 'react';
import {TouchableWithoutFeedback, Dimensions, StyleSheet, ScrollView, Keyboard, Text, View, Image, SafeAreaView, Button , Pressable, TextInput, FlatList} from 'react-native';
import Header from './Header';
import { createNativeStackNavigator} from '#react-navigation/native-stack';
import { useNavigation, useRoute } from '#react-navigation/native';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import constants from './constants';
import Icon from 'react-native-vector-icons/Feather';
export default function NewMemory(){
const [dateShow, setDateShow] = React.useState(false);
const [timeShow, setTimeShow] = React.useState(false);
const [date, setDate] = React.useState('');
const [time, setTime] = React.useState('');
function setDateWrapper(date){
console.log(date.toLocaleDateString());
setDate(date.toLocaleDateString());
setDateShow(false);
}
function setTimeWrapper(time){
time = time.toLocaleTimeString();
let tokens = time.split(':');
let ampm = tokens[tokens.length-1];
ampm = ampm.split(' ')[1];
tokens[2] = ampm;
setTime(tokens[0] + ':' + tokens[1] + ' ' + ampm);
setTimeShow(false);
}
return (
<View style={{width: '100%', /* borderColor:'green', borderWidth: 1 */}}>
<Header title='Send Capsule' backButton></Header>
<View style={{borderBottomColor:'grey', borderBottomWidth:1, display:'flex', flexDirection:'row', padding: 10}}>
<Icon name='image' size={70}></Icon>
<TouchableWithoutFeedback onPress={()=> {console.log('this message should appear on screen tap, but doesnt'); Keyboard.dismiss()}}>
<View style={{flex: 1, borderWidth: 3, borderColor: 'red'}}>
<TextInput
multiline
placeholder='Write a caption...'
style={{ flex: 1, padding:10, paddingTop: 12, paddingBottom: 12}}
maxHeight={240}
></TextInput>
</View>
</TouchableWithoutFeedback>
</View>
<View style={{ padding: 10}}>
<View>
<Text style={{marginBottom:5}}>Unlock Date</Text>
<Pressable onPress={()=>setDateShow(true)} style={{display: 'flex', flexDirection: 'row', alignItems:'center', padding: 10, borderRadius:5, backgroundColor: constants.inputFieldGreyBackground}}>
<Text style={date? null : {color: '#b5b5b5'}}>{date ? date : 'Date'}</Text>
</Pressable>
</View>
<View style={{height:10}}></View>
<Pressable onPress={()=>setTimeShow(true)} style={{display: 'flex', flexDirection: 'row', alignItems:'center', padding: 10, borderRadius:5, backgroundColor: constants.inputFieldGreyBackground}}>
<Text style={time? null : {color: '#b5b5b5'}}>{time ? time : 'Time (optional)'}</Text>
</Pressable>
<DateTimePickerModal isVisible={dateShow} display='spinner' mode='date' onCancel={()=>setDateShow(false)} onConfirm={(date)=> {setDateWrapper(date)}}></DateTimePickerModal>
<DateTimePickerModal isVisible={timeShow} display='spinner' mode='time' onCancel={()=>setTimeShow(false)} onConfirm={(time)=> {setTimeWrapper(time)}}></DateTimePickerModal>
</View>
</View>
);
}
Is there a reason why you must use "ToucheableWithoutFeedback"? I'd recommend you to use "Pressable" instead as suggested by official React Native docs on ToucheableWithoutFeedback.
React Native official documentation on ToucheableWithoutFeedback:
Do not use unless you have a very good reason.
There's two ways you can fix the issue.
1. Continue using ToucheableWithoutFeedback
You'll have to follow the documentation on how it should be used.
Note that you need to add {...props} in the <View /> component.
Importantly, TouchableWithoutFeedback works by cloning its child and
applying responder props to it. It is therefore required that any
intermediary components pass through those props to the underlying
React Native component. (From react native docs)
<TouchableWithoutFeedback onPress={()=> {console.log('hello'); Keyboard.dismiss()}}>
<View {...props} style={{flex: 1, borderWidth: 3, borderColor: 'red'}}>
<TextInput
multiline
placeholder='Write a caption...'
style={{ flex: 1, padding:10, paddingTop: 12, paddingBottom: 12}}
maxHeight={240}
/>
</View>
</TouchableWithoutFeedback>
2. Change ToucheableWithoutFeedback to Pressable.
Note that you don't need to pass {...props}.
<Pressable onPress={()=> {console.log('hello'); Keyboard.dismiss()}}>
<View style={{flex: 1, borderWidth: 3, borderColor: 'red'}}>
<TextInput
multiline
placeholder='Write a caption...'
style={{ flex: 1, padding:10, paddingTop: 12, paddingBottom: 12}}
maxHeight={240}
/>
</View>
</Pressable>
import React from 'react';
import {TouchableWithoutFeedback, Dimensions, StyleSheet, ScrollView, Keyboard, Text, View, Image, SafeAreaView, Button , Pressable, TextInput, FlatList,} from 'react-native';
import { createNativeStackNavigator} from '#react-navigation/native-stack';
import { useNavigation, useRoute } from '#react-navigation/native';
import DateTimePickerModal from 'react-native-modal-datetime-picker';
import Icon from 'react-native-vector-icons/Feather';
export default function App(){
const [dateShow, setDateShow] = React.useState(false);
const [timeShow, setTimeShow] = React.useState(false);
const [date, setDate] = React.useState('');
const [time, setTime] = React.useState('');
function setDateWrapper(date){
console.log(date.toLocaleDateString());
setDate(date.toLocaleDateString());
setDateShow(false);
}
function setTimeWrapper(time){
time = time.toLocaleTimeString();
let tokens = time.split(':');
let ampm = tokens[tokens.length-1];
ampm = ampm.split(' ')[1];
tokens[2] = ampm;
setTime(tokens[0] + ':' + tokens[1] + ' ' + ampm);
setTimeShow(false);
}
return (
<View style={{width: '100%', /* borderColor:'green', borderWidth: 1 */}}>
<View style={{borderBottomColor:'grey', borderBottomWidth:1, display:'flex', flexDirection:'row', padding: 10}}>
<Icon name='image' size={70}></Icon>
<TouchableWithoutFeedback onPress={()=> {console.log('hello'); Keyboard.dismiss()}}>
<View style={{flex: 1, borderWidth: 3, borderColor: 'red'}}>
<TextInput
multiline
placeholder='Write a caption...'
style={{ flex: 1, padding:10, paddingTop: 12, paddingBottom: 12}}
maxHeight={240}
></TextInput>
</View>
</TouchableWithoutFeedback>
</View>
<View style={{ padding: 10}}>
<View>
<Text style={{marginBottom:5}}>Unlock Date</Text>
<Pressable onPress={()=>setDateShow(true)} style={{display: 'flex', flexDirection: 'row', alignItems:'center', padding: 10, borderRadius:5, }}>
<Text style={date? null : {color: '#b5b5b5'}}>{date ? date : 'Date'}</Text>
</Pressable>
</View>
<View style={{height:10}}></View>
<Pressable onPress={()=>setTimeShow(true)} style={{display: 'flex', flexDirection: 'row', alignItems:'center', padding: 10, borderRadius:5, }}>
<Text style={time? null : {color: '#b5b5b5'}}>{time ? time : 'Time (optional)'}</Text>
</Pressable>
<DateTimePickerModal isVisible={dateShow} display='spinner' mode='date' onCancel={()=>setDateShow(false)} onConfirm={(date)=> {setDateWrapper(date)}}></DateTimePickerModal>
<DateTimePickerModal isVisible={timeShow} display='spinner' mode='time' onCancel={()=>setTimeShow(false)} onConfirm={(time)=> {setTimeWrapper(time)}}></DateTimePickerModal>
</View>
</View>
);
}
In the React Native application, the button continues to operate when the information is entered incorrectly on the member entry and registration page. The button is not activated again to re-enter information. Could you help?
In other words, when the information is entered incorrectly or missing, the registration button is rotating continuously.
Please review the screenshot and codes.
Screenshot:
[![Screen shot with the UI][1]][1]
My codes are:
import React from 'react';
import { StyleSheet, Text, View, Image, Dimensions, TextInput, TouchableOpacity, ActivityIndicator } from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import Icon from 'react-native-vector-icons/Ionicons';
const { height, width } = Dimensions.get('window');
const LogoImg = require('../assets/img/challengelogo.png');
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scrollview'
import {connect} from 'react-redux';
import * as appActions from './actions';
export class signupView extends React.Component {
constructor(props){
super(props);
this.state = {
checkboxChecked: false,
checkboxIcon: 'ios-square-outline'
}
}
render() {
const { container, innerContainer, innerImageContainer, buttonView , buttonViewRegister, innerButtonTextView, innerButtonView, termsView} = styles;
return (
<LinearGradient
colors={['#f9a149', '#e86e52', '#d6375c']}
style={ container }>
<KeyboardAwareScrollView
showsVerticalScrollIndicator={false}
keyboardShouldPersistTaps="always"
style={styles.scrollContainer}>
<View style={innerContainer}>
<Image
source={LogoImg}
style={{ width: width*0.45, height: width*0.55 }}
resizeMode={'contain'}
/>
<View style={{flexDirection:'row', alignItems:'center'}}>
<Text style={{color:'#fff', fontSize:18, margin:10, textDecorationLine:'underline'}} >KAYIT OL</Text>
</View>
<View style={styles.searchSection}>
<Icon style={styles.searchIcon} name="ios-person-add" size={30} color="#000"/>
<TextInput
style={styles.input}
placeholder="Kullanıcı Adı"
underlineColorAndroid="transparent"
autoCapitalize = 'none'
autoCorrect = {false}
value = {this.props.r_name}
onChangeText={this._onNameChanged.bind(this)}
autoFocus = { true }
blurOnSubmit = { false }
returnKeyType = { "next" }
onSubmitEditing = {() => {this.mailTextInput.focus()} }
/>
</View>
<View style={styles.searchSection}>
<Icon style={styles.searchIcon} name="ios-mail-outline" size={30} color="#000"/>
<TextInput
ref={(input) => { this.mailTextInput = input; }}
style={styles.input}
placeholder="Mail Adresi"
underlineColorAndroid="transparent"
keyboardType="email-address"
autoCapitalize = 'none'
autoCorrect = {false}
value = {this.props.r_email}
onChangeText={this._onEmailChanged.bind(this)}
blurOnSubmit = { false }
returnKeyType = { "next" }
onSubmitEditing = {() => {this.passwordTextInput.focus()} }
/>
</View>
<View style={styles.searchSection}>
<Icon style={styles.searchIcon} name="md-lock" size={30} color="#000"/>
<TextInput
ref={(input) => { this.passwordTextInput = input; }}
style={styles.input}
placeholder="Şifre"
onChangeText={(searchString) => {this.setState({searchString})}}
underlineColorAndroid="transparent"
secureTextEntry={true}
autoCapitalize = 'none'
autoCorrect = {false}
value = {this.props.r_password}
onChangeText={this._onPasswordChanged.bind(this)}
/>
</View>
{ !this.props.isloadingSignup &&
<TouchableOpacity onPress={this._onSignUpPress}>
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<Text style={{ color:'#FFF', fontSize: 15}}>Kayıt Ol</Text>
</View>
</View>
</TouchableOpacity>
||
<TouchableOpacity>
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<ActivityIndicator color="white" size='small' />
</View>
</View>
</TouchableOpacity>
}
<TouchableOpacity onPress={this._onPressTerms}>
<View style={ [termsView]}>
<Icon name={this.state.checkboxChecked ? 'ios-checkbox': 'ios-square-outline'} size={30} color="#000" />
<Text style={{ color:'#FFF', fontSize: 15, marginLeft: 10}}><Text onPress={this._onPressTermsConditions } style={{ textDecorationLine: "underline"}}> Kullanım koşullarını</Text> Kabul Ediyorum.</Text>
</View>
</TouchableOpacity>
</View>
</KeyboardAwareScrollView>
</LinearGradient>
);
}
_onSignUpPress = () => {
if(this.state.checkboxChecked) {
var registerBody = {
email: this.props.r_email,
password: this.props.r_password,
password_confirmation: this.props.r_password,
name: this.props.r_name
};
this.props.dispatch(appActions.register(registerBody));
} else {
alert("Lütfen önce Kullanıcı şartlarını kabul edin.");
}
}
_onEmailChanged = (email) => {
this.props.dispatch(appActions.emailChanged(email));
}
_onNameChanged = (name) => {
this.props.dispatch(appActions.nameChanged(name));
}
_onPasswordChanged = (password) => {
this.props.dispatch(appActions.passwordChanged(password));
}
_onPressTerms = () => {
this.setState({ checkboxChecked: !this.state.checkboxChecked })
}
_onPressTermsConditions = () => {
this.props.navigator.push({
screen: 'challenge.TermsOfUse',
navigatorStyle: {
navBarHidden: true
}
});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'flex-start',
},
scrollContainer:{
flex: 1,
},
innerContainer:{
flexDirection:'column',
alignItems:'center',
marginTop: height*0.08,
},
searchSection: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
width:width*0.7,
marginTop:7
},
searchIcon: {
paddingTop:5,
paddingBottom:5,
paddingLeft:10,
paddingRight:10
},
input: {
flex: 1,
backgroundColor: '#fff',
color: '#424242',
justifyContent:'center',
},
buttonView:{
width: width*0.7,
marginTop:20,
flexDirection:'row',
},
buttonViewRegister:{
backgroundColor:"#2b74a7"
},
innerButtonView:{
backgroundColor:'#bab9b9',
width:45,
height:42,
justifyContent:'center',
alignItems:'center'
},
innerButtonTextView:{
flex:1,
justifyContent:'center',
alignItems:'center'
},
termsView:{
width: width*0.8,
marginTop:20,
flexDirection:'row',
justifyContent:'center',
alignItems:'center'
}
});
const mapStateToProps = ({ signup }) => {
return { r_email, r_password, r_name, isloadingSignup } = signup;
};
export default connect(mapStateToProps)(signupView);
Firstly, thanks for your response. I couldn't put the codes here because it crossed the character limit. So you can review the action content from this link. http://karahankaraman.com/actions/index.js
I think you are overcomplicating your signup page. Do you really need to dispatch to redux to handle your signup logic? You might need to show us your actions.js file if this continues.
Meanwhile do this:
{ !this.props.isloadingSignup ?
<TouchableOpacity onPress={this._onSignUpPress}>
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<Text style={{ color:'#FFF', fontSize: 15}}>Kayıt Ol</Text>
</View>
</View>
</TouchableOpacity>
:
<View style={ [buttonView, buttonViewRegister]}>
<View style={innerButtonView}>
<Icon name="ios-person-add" size={30} color="#000" />
</View>
<View style={innerButtonTextView}>
<ActivityIndicator color="white" size='small' />
</View>
</View>
}