Alright. So i'm new to react native and im learning on creating a signup authentication with Firebase. I have three files: Signup.js, Login.js and Profile.js. In my Signup screen when i call on the function handleSignUp onPress i get:
Cannot read property 'navigate' of undefined.
I assume that i need to get out of the function scope to the global scope? I'm not sure what i'm missing here or how to tackle it. any advice?
Here's my code.
{*Signup.js*}
import React from 'react'
import { View, TextInput, StyleSheet, TouchableOpacity, Text } from 'react-native'
import { createAppContainer, createSwitchNavigator } from 'react-navigation'
import { withNavigation } from 'react-navigation';
import Firebase from '../config/Firebase'
class Signup extends React.Component {
state = {
name: '',
email: '',
password: ''
}
handleSignUp = () => {
const { email, password } = this.state
Firebase.auth()
.createUserWithEmailAndPassword(email, password)
.then(()=>this.props.navigation.navigate('Profile'))
.catch(error => console.log(error))
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.inputBox}
value={this.state.name}
onChangeText={name => this.setState({ name })}
placeholder='Full Name'
/>
<TextInput
style={styles.inputBox}
value={this.state.email}
onChangeText={email => this.setState({ email })}
placeholder='Email'
autoCapitalize='none'
/>
<TextInput
style={styles.inputBox}
value={this.state.password}
onChangeText={password => this.setState({ password })}
placeholder='Password'
secureTextEntry={true}
/>
<TouchableOpacity style={styles.button} onPress={this.handleSignUp}>
<Text style={styles.buttonText}>Signup</Text>
</TouchableOpacity>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
},
inputBox: {
width: '85%',
margin: 10,
padding: 15,
fontSize: 16,
borderColor: '#d3d3d3',
borderBottomWidth: 1,
textAlign: 'center'
},
button: {
marginTop: 30,
marginBottom: 20,
paddingVertical: 5,
alignItems: 'center',
backgroundColor: '#FFA611',
borderColor: '#FFA611',
borderWidth: 1,
borderRadius: 5,
width: 200
},
buttonText: {
fontSize: 20,
fontWeight: 'bold',
color: '#fff'
},
buttonSignup: {
fontSize: 12
}
})
export default Signup
Login.js
import React from 'react'
import { View, TextInput, StyleSheet, TouchableOpacity, Text, Button } from 'react-native'
import { createAppContainer, createSwitchNavigator } from 'react-navigation'
class Login extends React.Component {
state = {
email: '',
password: ''
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.inputBox}
value={this.state.email}
onChangeText={email => this.setState({ email })}
placeholder='Email'
autoCapitalize='none'
/>
<TextInput
style={styles.inputBox}
value={this.state.password}
onChangeText={password => this.setState({ password })}
placeholder='Password'
secureTextEntry={true}
/>
<TouchableOpacity style={styles.button}>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
<Button
title="Don't have an account yet? Sign up"
onPress={() => this.props.navigation.navigate('Signup')}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
},
inputBox: {
width: '85%',
margin: 10,
padding: 15,
fontSize: 16,
borderColor: '#d3d3d3',
borderBottomWidth: 1,
textAlign: 'center'
},
button: {
marginTop: 30,
marginBottom: 20,
paddingVertical: 5,
alignItems: 'center',
backgroundColor: '#F6820D',
borderColor: '#F6820D',
borderWidth: 1,
borderRadius: 5,
width: 200
},
buttonText: {
fontSize: 20,
fontWeight: 'bold',
color: '#fff'
},
buttonSignup: {
fontSize: 12
}
})
export default Login
Profile.js
import React from 'react'
import { View, Text, StyleSheet } from 'react-native'
class Profile extends React.Component {
render() {
return (
<View style={styles.container}>
<Text>Profile Screen</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
}
})
export default Profile
From the docs: https://reactnavigation.org/docs/en/hello-react-navigation.html
The current SignUp code is only a React.Component.
Make sure you're creating both an AppNavigator and createAppContainer() per react-navigation documentation.
import React from 'react';
import { View, Text } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
class HomeScreen extends React.Component {
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}
}
const AppNavigator = createStackNavigator({
Home: {
screen: HomeScreen,
},
});
export default createAppContainer(AppNavigator);
Related
When Using react-navigation version 4.1.1
When navigating from one screen to another screen it is fluctuating and i am using ImageBackground there ,so first white blank screen appears after that imagebackground is loading which is very slow and i can easily see the transition over there .
I dont know what's the exact issue is there.
And for this new version i have to install libraries also for react navigation i.e.react-native screens,animated and maskedView ,safeareacontext.
So please any one know about this please let me know ..
Thanks in advance .
Here is a video for my app where i am getting image loading issue...
https://drive.google.com/open?id=16bdmxOC342uCQl3UL_hB8K0wznpbedge
Here is my APP.js File where i have created stack navigator..
import React, { Component } from 'react';
import { createAppContainer } from "react-navigation"
import { createStackNavigator } from 'react-navigation-stack';
import WelcomeScreen from './Screens/WelcomeScreen';
import Walkthorugh from './Screens/Walkthrough';
import Login from './Screens/Login';
import Signup from './Screens/Signup';
import Profile from './Screens/Profile';
import Wishlist from './Screens/Wishlish';
import Home from './Screens/Home';
import Cart from './Screens/Cart';
const notificationsel = require('./Screens/icons/notificationsel.png');
import { createBottomTabNavigator } from 'react-navigation-tabs';
import { enableScreens } from 'react-native-screens';
import { useScreens } from 'react-native-screens';
import {
StyleSheet,
Easing,
View, Animated, FlatList,
Text, Image, Alert, YellowBox, Button, ImageBackground,
TouchableWithoutFeedback, TouchableOpacity
} from 'react-native';
const welcomeStack = createStackNavigator({
Welcome:{screen:WelcomeScreen
},
});
const homeStack = createStackNavigator({
Home:{screen:Home
},
});
const profileStack = createStackNavigator({
Profile:{screen:Profile,
navigationOptions:{header:null}},
});
const cartStack = createStackNavigator({
Cart:{screen:Cart,
navigationOptions:{header:null}},
});
const wishlistStack = createStackNavigator({
Wishlist:{screen:Wishlist,
navigationOptions:{header:null}},
});
const HomeTabNavigator = createBottomTabNavigator({
Home : homeStack,
Profile : profileStack,
Cart : cartStack,
Wishlist : wishlistStack,
},
{
defaultNavigationOptions: ({ navigation }) => ({
tabBarOnPress: ({ navigation, defaultHandler }) => {
console.log('onPress:', navigation.state.routeName);
// if(navigation.state.routeName=='CallNow'){
// Linking.openURL(`tel:${'9414036555'}`)
// console.log("CallNow")
// }
defaultHandler()
},
tabBarIcon: ({ focused, horizontal, tintColor }) => {
const { routeName } = navigation.state;
let iconName;
if (routeName === 'Home') {
iconName = focused ? notificationsel : notificationsel;
}
else if (routeName === 'Profile') {
iconName = focused ? notificationsel : notificationsel;
}
else if (routeName === 'Cart') {
iconName = focused ? notificationsel : notificationsel;
}
else if (routeName === 'Wishlist') {
iconName = focused ? notificationsel : notificationsel;
}
// You can return any component that you like here!
return <Image source={iconName} style={{width:22,height:22}}/>
;
},
}),
tabBarOptions:{
activeTintColor: 'blue',
inactiveTintColor: '#000',
showLabel:true,
style:{backgroundColor:'#fff',padding:5}
},
}
);
const AppNavigator = createStackNavigator(
{
Home: {
screen: HomeTabNavigator,
// navigationOptions:{header:null}
},
Walkthorugh:{
screen:Walkthorugh,
// navigationOptions:{header:null}
},
Welcome:{
screen:WelcomeScreen,
// navigationOptions:{header:null}
},
Login:{
screen:Login,
},
Signup:{
screen:Signup,
// navigationOptions:{header:null}
},
},
{
headerMode:'none',
initialRouteName: "Walkthorugh",
cardStyle: {backgroundColor: "transparent", opacity: 1 },
defaultNavigationOptions: {
gesturesEnabled: false,
cardStyle: {backgroundColor: "transparent", opacity: 1 },
swipeEnabled: false,
animationEnabled: false,
},
}
);
const AppContainer = createAppContainer(AppNavigator);
export default class App extends Component {
render() {
return (
<AppContainer />
)
}
}
And this is my Login.js ..
import React, { Component } from 'react';
import {
StyleSheet,
Platform,
View, ActivityIndicator, FlatList,
Text, Image, Dimensions, Keyboard, TextInput, ImageBackground,
StatusBar, TouchableOpacity
} from 'react-native';
import { NavigationActions, StackActions } from 'react-navigation';
const { width, height } = Dimensions.get('window');
const app_icon = require('./icons/app_icon.png')
const loginbg = require('./icons/loginbg.jpg')
const fashionbot = require('./icons/fashionbot.png')
import { Api_const, App_colors } from './Const/Const.js';
import { ScrollView } from 'react-native-gesture-handler';
import LinearGradient from 'react-native-linear-gradient';
export default class Login extends Component {
static navigationOptions = {
headerTitle: 'Login',
// headerLeft: (
// <View style={{ flexDirection: "row", marginLeft: 20, marginRight: 20 }}>
// <TouchableWithoutFeedback>
// <Image source={require('../assets/Hamburger.png')} >
// </Image>
// </TouchableWithoutFeedback>
// </View>
// ),
headerStyle: { borderBottomWidth: 0, marginTop: (Platform.OS === 'ios') ? 0 : 0 },
headerBackTitle: " "
};
constructor(props) {
super(props);
this.state = {
isLoading: false,
email: '',
password: '',
}
}
onClick_Login = () => {
var action = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Home',params:{test:'test'} })]
});
this.props.navigation.dispatch(action);
// setTimeout(()=>{
// this.props.navigation.dispatch(action);
// },
// 400);
}
render() {
if (this.state.isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" />
</View>
);
}
return (
<LinearGradient colors={[App_colors.purple, App_colors.pink, App_colors.pink]} style={{flex:1}}>
<ScrollView ref="scrollView" style={{ flex:1 }} bounces={false}>
<StatusBar hidden={true} backgroundColor={App_colors.purple} barStyle="dark-content" />
<View style={{ flex:1,height}}>
<ImageBackground source={loginbg} style={{height }}>
<View style={{height }}>
<View style={{ flexDirection: 'row', margin: 15 }}>
<Image style={{ flex: 0.3, height: 90, alignItems: 'center', justifyContent: 'center', alignSelf: 'center' }} resizeMode={"contain"} source={app_icon} />
<Image style={{ flex: 1, alignItems: 'center', justifyContent: 'center', alignSelf: 'center' }} resizeMode={"contain"} source={fashionbot} />
</View>
<View style={{flex:1, justifyContent: 'center', marginLeft: 25, marginRight: 25 }}>
<Text style={{ fontSize: 22, color: '#fff', alignItems: 'center', alignSelf: 'center' }}>{'Login'}</Text>
<Text style={{ fontSize: 16, color: '#fff', marginTop: 15 }}>{'Email'}</Text>
<TextInput style={{ fontSize: 14, height: 40, marginLeft: 0, marginRight: 0, color: 'white' }}
value={this.state.email}
onChangeText={(text) => this.setState({ email: text })}
placeholder={'Your Email'}
placeholderTextColor={App_colors.white}
underlineColorAndroid={'white'}
textContentType={'username'}
keyboardType='email-address'
caretHidden={false}
onSubmitEditing={() => { Keyboard.dismiss() }}
/>
{/* PASSWORD */}
<Text style={{ fontSize: 16, color: '#fff', marginTop: 15 }}>{'Password'}</Text>
<TextInput style={{ fontSize: 14, height: 40, marginLeft: 0, marginRight: 0, color: 'white' }}
value={this.state.password}
onChangeText={(text) => this.setState({ password: text })}
placeholder={'*********'}
placeholderTextColor={App_colors.white}
underlineColorAndroid={'white'}
secureTextEntry={true}
caretHidden={false}
onSubmitEditing={() => { Keyboard.dismiss() }}
/>
<Text style={{ fontSize: 16, color: '#fff', marginTop: 5 }}>{'Forgot Password?'}</Text>
<TouchableOpacity style={{ justifyContent: 'center',alignSelf:'center', marginBottom: 10, marginTop: 30, width: width - 100, marginLeft: 0, marginRight: 0, alignItems: 'center', borderRadius: 25, borderWidth: 0, paddingTop: 15, paddingBottom: 15, backgroundColor: 'white' }}
onPress={this.onClick_Login}>
<Text style={{ fontSize: 16, color: App_colors.purple }}>{'Log in'}</Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
</View>
</ScrollView>
</LinearGradient>
);
}
}
in development mode react-native will show white screen. But in production, it won't so don't worry. it is normal.
about navigation I can't be sure but share the code or demo(image/video).
I'm using deeplinking in react-native in order to redirect the user to a youtube channel. But when I'm going back to my app, I have a blank screen, how can I make the user going back to the homeScreen ?
Here is my youtube code :
import React from 'react';
import { View, Text, Linking } from 'react-native';
import Acceuil from './Accueil';
class ChaineYT extends React.Component {
state = {
isLoading:false,
isLinked: false
}
componentDidMount = () => {
Linking.openURL('vnd.youtube://' + 'www.youtube.com/channel/UC1UpcbyFVTZTDrvdjNmSzSg')
this.setState(isLoading=true, isLinked=true);
if(this.state.isLoading && this.state.isLinking){
return this.props.navigation.navigate("Acceuil")
}
}
render() {
return (
<View>
</View>
)
}
}
export default ChaineYT
I'm not sure about the states that I'm using.
Edit : I've updated with the Accueil.js screen.
import React from 'react';
import { StyleSheet, View, TextInput, Button, Text, FlatList, ListView, Linking, StatusBar } from 'react-native';
import voyantes from '../Helpers/voyantesData';
import VoyanteItem from './VoyanteItem';
import MyButton2 from './MyButton2';
const numColumns = 2;
class Accueil extends React.Component {
_displayDetailForVoyante = (idVoyante,photo, specialite, description, name) => {
console.log("Display film with id " + idVoyante);
this.props.navigation.navigate("VoyanteProfil", { idVoyante: idVoyante,photo: photo,specialite:specialite,description:description, name:name });
}
render() {
return (
<View style={styles.main_container}>
<View style={{ flexDirection:'row', justifyContent: 'space-around', marginVertical: 8 }}>
<MyButton2 style={{}} text={"Voyance privée\nouvert 24h/24\n01 44 01 77 01"} icone='icone-transfert' onPress={() => { Linking.openURL('tel:0144017701'); }}/>
<MyButton2 text={"Voyance sans CB\nouvert 24h/24\n32 32"} icone='icone-sonnerie' onPress={() => { Linking.openURL('tel:3232'); }}/>
</View>
<FlatList style={styles.flatList}
data={voyantes}
keyExtractor={(item) => item.id.toString()}
renderItem={({item}) => <VoyanteItem voyante={item} displayDetailForVoyante={this._displayDetailForVoyante} />}
numColumns={numColumns} />
</View>
)
}
}
const styles = StyleSheet.create({
main_container: {
flex: 1,
backgroundColor: '#dfdee1',
backgroundColor: 'white',
flexDirection: 'column',
},
textinput: {
marginLeft: 5,
marginRight: 5,
height: 50,
borderColor: '#000000',
borderWidth: 1,
paddingLeft: 5,
backgroundColor: 'white'
},
button: {
backgroundColor: '#EF3934',
borderColor: '#EF3934',
marginLeft: 20,
marginRight: 20
},
text: {
backgroundColor: '#EF3934',
borderColor: '#EF3934',
marginLeft: 20,
marginRight: 20
},
flatList: {
flex: 1,
flexDirection: 'column',
alignContent: 'flex-start',
//justifyContent: 'flex-start',
//alignItems: 'flex-start'
}
})
export default Accueil
``
I found solution :
In your ChaineYT you have written below line :
this.setState(isLoading=true, isLinked=true);
replace it with :
this.setState({isLoading:true, isLinked:true});
I am new to react native, and I have created one sample login form. In this form i want to align total view to center. I tried this way but not working, Can You guide me how to achieve this.
My login class is
import React, {Component} from 'react';
import {AppRegistry,Text, View,TextInput,TouchableOpacity,StyleSheet} from 'react-native';
export default class Login extends Component{
render(){
return(
<View style={styles.container}>
<TextInput style={styles.textInput} placeholder="Acc No/User ID"/>
<TextInput style={styles.textInput} placeholder="Password"/>
<TouchableOpacity style={styles.btn} onPress={this.login}><Text>Log In</Text></TouchableOpacity>
</View>
);
}
login=()=>{
alert("testing......");
// this.props.navigation.navigate('Second');
}
}
AppRegistry.registerComponent('Login', () => Login);
const styles = StyleSheet.create({
container:{
justifyContent: 'center',
alignItems: 'center',
},
header: {
fontSize: 24,
marginBottom: 60,
color: '#fff',
fontWeight: 'bold',
},
textInput: {
alignSelf: 'stretch',
padding: 10,
marginLeft: 80,
marginRight:80,
},
btn:{
alignSelf: 'stretch',
backgroundColor: '#01c853',
padding: 10,
marginLeft: 80,
marginRight:80,
alignItems: 'center',
}
});
And the following is the screen shot of above code.
And i tried with the bellow code, but not working
container:{
justifyContent: 'center',
alignItems: 'center',
flex:1
},
So please help me, how to do this?
Thanks In Advance..
Use the flex display : https://css-tricks.com/snippets/css/a-guide-to-flexbox/
import React, { Component } from 'react';
import { AppRegistry, Text, View, TextInput, TouchableOpacity, StyleSheet } from 'react-native';
export default class Login extends Component {
render() {
return (
<View style={styles.container}>
<TextInput style={styles.textInput} placeholder="Acc No/User ID" />
<TextInput style={styles.textInput} placeholder="Password" />
<TouchableOpacity style={styles.btn} onPress={this.login}><Text>Log In</Text></TouchableOpacity>
</View>
);
}
login = () => {
alert("testing......");
// this.props.navigation.navigate('Second');
}
}
AppRegistry.registerComponent('Login', () => Login);
const styles = StyleSheet.create({
container: {
display: 'flex',
flexDirection: 'column',
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
header: {
fontSize: 24,
color: '#fff',
fontWeight: 'bold',
},
textInput: {
padding: 10,
textAlign: 'center',
},
btn: {
backgroundColor: '#01c853',
paddingVertical: 10,
paddingHorizontal: 50,
}
});
And by the way, you could have easily found an answer with a simple search (Vertically center view react-native) : https://moduscreate.com/blog/aligning-children-using-flexbox-in-react-native/
just add flex :1 to your container style
container:{
flex:1,
justifyContent: 'center',
alignItems: 'center',
}
import React,{Component} from 'react';
import {View,Text,TextInput, Button,StyleSheet,Alert} from 'react-native';
class App extends Component{
state = {
userId:'',
password:'',
};
render(){
return(
<View style={styles.container}>
<View>
</View>
<View>
<TextInput
placeholder="User ID"
style={styles.loginTextInput}
onChangeText={(value) => this.setState({userId: value})}
value={this.state.userId}
></TextInput>
<TextInput
placeholder="Password"
style={styles.loginTextInput}
onChangeText={(value)=>this.setState({password:value})}
></TextInput>
<Button
title="Login"
style={styles.loginBtn}
onPress={this.loginCheck}
></Button>
</View>
</View>
)
}
loginCheck=()=>{
if((this.state.userId=='admin') && (this.state.password=='admin')){
Alert.alert("Login Success");
}else{
Alert.alert("User and password is not match\n Please try again");
}
}
}
export default App;
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
},
loginTextInput:{
borderColor:'#ebe9e6',
borderWidth:1,
margin:5,
},
loginBtn:{
backgroundColor: '#01c853',
paddingVertical: 10,
paddingHorizontal: 50,
}
})
I am new to react native. I tried using the createStackNavigator module. However, I do not know why my onClick function is not directing me to the required screen. Here are my codes are shown below:
mySpaceRouter.js
import {createStackNavigator} from 'react-navigation'
import SubscriptionScreen from './subscribed'
import MySpaceScreenRT from './myspace'
import React, {Component} from 'react'
const RootStack = createStackNavigator(
{
MySpace : MySpaceScreenRT,
subscribed : SubscriptionScreen,
navigationOptions:{
header:{ visible:false }
}
},
{
initialRouteName : 'MySpace',
},
)
class MySpaceScreen extends Component{
render(){
return(
<RootStack />
)
}
}
export default MySpaceScreen;
mySpace.js
import React, { Component } from 'react'
import { StyleSheet, Text, View, ScrollView, TouchableOpacity } from 'react-native'
import { Avatar, Button, Icon } from 'react-native-elements'
import MyButton from '../Button'
class MySpaceScreenRT extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
<View style={styles.textHolder}>
<Text style={styles.headerText}>My Space</Text>
</View>
</View>
<View style={styles.boxContainer} >
<ScrollView style={styles.scrollContainer}>
<View style={styles.profileContainer}>
<Avatar
large
rounded
title="CR"
onClick={() =>this.props.navigation.navigate('subscribed')}
activeOpacity={0.7}
/>
<Text style={styles.profileName}>Christaino Ronaldo </Text>
</View>
<MyButton text='Subscribed' icon='ios-play' />
<MyButton text='Downloads' icon='ios-folder-open' onPress ={() => console.log('Works!')} />
<MyButton text='History' icon='ios-timer-outline' />
<MyButton text='Rate Our App' icon='ios-star-half' />
</ScrollView>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'column',
flex: 1,
},
header: {
height: 70,
backgroundColor: '#780c1c',
elevation: 5,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
boxContainer: {
flex: 1,
flexDirection: 'column',
},
textHolder: {
},
headerText: {
fontSize: 20,
color: 'white'
},
profileContainer: {
height: 150,
borderColor : '#696969',
borderBottomWidth: 0.5,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'transparent',
},
profileName: {
position: 'relative',
zIndex: 1,
fontSize: 16,
color: '#000000',
alignSelf: 'center',
marginTop: 10,
marginLeft: 10
},
scrollContainer: {
flexDirection: 'column',
},
icons: {
marginTop: 10
},
Text: {
fontSize: 18,
alignSelf: 'center',
padding: 10
}
})
export default MySpaceScreenRT;
subscribed.js
import React, {Component} from 'react'
import {StyleSheet, Text, View} from 'react-native'
class SubscriptionScreen extends Component {
render(){
return(
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>SubscriptionScreen!</Text>
</View>
)
}
}
export default SubscriptionScreen;
Thank you.
With react-native you use onPress() not onClick().
onPress={() =>this.props.navigation.navigate('subscribed')}
For each screen in the stack you have to create an entry so you should do something like this:
const RootStack = createStackNavigator({
MySpace: {
screen: MySpace,
navigationOptions: ({ navigation }) => ({
title: "My Space" ,
header:{ visible:false }
}),
},
subscribed: {
screen: SubscriptionScreen,
navigationOptions: ({ navigation }) => ({
title: "" ,
header:{ visible:false }
}),
}
},{
initialRouteName : 'MySpace',
})
in addition to that you have to change onClick to onPress
I have a react native screen where 2 text inputs are added by default, while 2 text inputs are added on button press only.
I am able to add text to the first 2 text inputs, but the other 2 are not accepting text, they accept text only when "Add another car" button is pressed again.
What am I missing? Why is the view not re-rendered when I add text.
CarReg.js
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TextInput
} from 'react-native';
var Button = require('./Button');
var Parse = require('parse/react-native');
class CarReg extends Component {
constructor(props) {
super(props);
this.state = {
carNumber1: "",
carState1: "",
carNumber2: "",
carState2: "",
errorMessage: "",
carEntry: <View/>,
};
}
render() {
const { page } = this.state;
return (
<View style={styles.container}>
<Text
style={[styles.titleContainer, {marginBottom: 30}]}>
Please register your cars, you can add up-to 2 cars </Text>
<Text style={styles.titleContainer}> License plate number: </Text>
<TextInput
style={styles.textInputContainer}
onChangeText={(text) => this.setState({carNumber1: text})}
value={this.state.carNumber1}/>
<Text style={styles.titleContainer}> State: </Text>
<TextInput
style={styles.textInputContainer}
onChangeText={(text) => this.setState({carState1: text})}
value={this.state.carState1}/>
{this.state.carEntry}
<Text>{this.state.errorMessage}</Text>
<Button text="Add another car" onPress={this.onAddCarPress.bind(this)}/>
<Button text="Submit" onPress={this.onSubmitPress.bind(this)}/>
<Button text="I don't have a car" onPress={this.onNoCarPress.bind(this)}/>
</View>
);
}
onAddCarPress() {
this.setState({carEntry:
<View style={styles.addCarView}>
<Text style={styles.titleContainer}> License plate number: </Text>
<TextInput
style={styles.textInputContainer}
onChangeText={(text) => this.setState({carNumber2: text})}
value={this.state.carNumber2}/>
<Text style={styles.titleContainer}> State: </Text>
<TextInput
style={styles.textInputContainer}
onChangeText={(text) => this.setState({carState2: text})}
value={this.state.carState2}/>
</View>
})
}
onSubmitPress() {
this.props.navigator.push({name: 'main'});
}
onNoCarPress() {
this.props.navigator.push({name: 'main'});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
addCarView: {
backgroundColor: '#F5FCFF',
justifyContent: 'center',
alignItems: 'center',
},
titleContainer: {
fontSize: 20,
fontFamily: 'Helvetica',
},
textInputContainer: {
padding: 4,
margin: 5,
borderWidth: 1,
borderRadius: 10,
width: 200,
height: 40,
fontFamily: 'Helvetica',
alignSelf: 'center',
marginBottom: 10,
marginTop: 10,
},
});
module.exports = CarReg;
Button.js
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
TouchableHighlight,
} from 'react-native';
class Button extends Component {
constructor(props) {
super(props);
}
render() {
return (
<TouchableHighlight
style={styles.container}
onPress={this.props.onPress}
underlayColor ='gray'>
<Text style={styles.textContainer}>{this.props.text}</Text>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
marginTop: 10,
padding: 5,
borderWidth: 1,
borderRadius: 10,
},
textContainer: {
fontFamily: 'Helvetica',
justifyContent: 'center',
alignSelf: 'center',
textAlign: 'center',
flex:1,
fontSize: 20,
}
});
module.exports = Button;
I created the demo of your code on the rnplay. (only ios version.)
I think it's not the good idea to push html to your state. The state is for the data like an array, a boolean and templates (strings). This is only my opinion, of course.
After you click to submit button, look at the console.