I am having a problem with this little piece of code. I have almost searched about this error everywhere but it did not solved my problem. I have used all the methods given by experts regarding tenter image description herehat problem. Please If anyone can help.
///app.js
import {
createStackNavigator,
createAppContainer
} from 'react-navigation';
import React, {Component} from 'react';
import {AppRegistry} from 'react-native';
import WelcomeScreen from './Components/Welcome/Welcome';
import SignInScreen from './Components/SingIn/SingIn';
import SignUpScreen from './Components/SingUp/SingUp';
import ContinueAsGuestScreen from './Components/ContinueAsGuest/ContinueAsGuest';
const RootStack = createStackNavigator({
WelcomeScreen: {
WelcomeScreen: WelcomeScreen
},
SignInScreen: {
SignInScreen: SignInScreen
},
SignUpScreen: {
SignUpScreen: SignUpScreen
},
ContinueAsGuestScreen: {
ContinueAsGuestScreen: ContinueAsGuestScreen
},
});
const App = createAppContainer(RootStack);
export default App;
**I have used all the techniques specially exporting things I found but of no help*
Here is Welcom.js
import React, { Component } from 'react';
import { Platform, AppRegistry, StyleSheet, Text, View, TextInput, TouchableOpacity } from 'react-native';
import symbolicateStackTrace from 'react-native/Libraries/Core/Devtools/symbolicateStackTrace';
import { ScrollView } from 'react-native-gesture-handler';
export default class Welcome extends Component {
static navigatonOptions =
{ title: 'Welcome Screen' };
constructor(props) {
super(props);
this.handleButton = this.handleButton.bind(this);
state =
{
Firstname: '',
Lastname: '',
EmailAddress: '',
PhoneNumber: '',
CompanyName: '',
OtherEmailAddress: ''
}
}
handleFirstName = (text) => {
this.setState({ FirstName: text })
}
handleLastName = (text) => {
this.setState({ Lastname: text })
}
handleEmailAddress = (text) => {
this.setState({ EmailAddress: text })
}
handlePhoneNumber = (text) => {
this.setState({ PhoneNumber: text })
}
handleCompanyName = (text) => {
this.setState({ CompanyName: text })
}
handleOtherEmailAddress = (text) => {
this.setState({ OtherEmailAddress: text })
}
handleButton = () => {
this.props.navigation.navigate("SignInScreen");
}
render() {
return (
<ScrollView style={styles.container} >
<View style={styles.header}>
<Text style={{ fontSize: 20 }}> Profile </Text>
</View>
<View>
<Text style={{ fontSize: 20, alignSelf: "center" }}> Welcome here </Text>
</View>
<Text>FIRST NAME *</Text>
<TextInput style={styles.input}
placeholder="Firstname"
placeholderTextColor="#9a73ef"
AutoCapitalization="none"
onChangeText={this.handleFirstName}
/>
<Text>LAST NAME *</Text>
<TextInput style={styles.input}
placeholder="LastName"
placeholderTextColor="#9a73ef"
AutoCapitalization="none"
onChangeText={this.handleLastName}
/>
<Text>Email Address *</Text>
<TextInput style={styles.input}
placeholder="Email Address"
placeholderTextColor="#9a73ef"
AutoCapitalization="none"
onChangeText={this.handleEmailAddress}
/>
<Text>PHONE NUMBER *</Text>
<TextInput style={styles.input}
placeholder="Phone Number"
placeholderTextColor="#9a73ef"
AutoCapitalization="none"
onChangeText={this.handlePhoneNumber}
/>
<Text>COMPANY NAME *</Text>
<TextInput style={styles.input}
placeholder="Company Name"
placeholderTextColor="#9a73ef"
AutoCapitalization="none"
onChangeText={this.handleCompanyName}
/>
<Text>OTHER EMAIL ADDRESS *</Text>
<TextInput style={styles.input}
placeholder="Other Email Address"
placeholderTextColor="#9a73ef"
AutoCapitalization="none"
onChangeText={this.handleOtherEmailAddress}
/>
<TouchableOpacity style={styles.submitButton2} onPress={() => this.handleButton} >
<Text style={styles.submitButtonText}> Save </Text>
</TouchableOpacity>
</ScrollView>
);
}
}
I think you're creating the navigator uncorrectly in createStackNavigator(). Try this:
const RootStack = createStackNavigator({
WelcomeScreen: {
screen: WelcomeScreen
},
SignInScreen: {
screen: SignInScreen
},
SignUpScreen: {
screen: SignUpScreen
},
ContinueAsGuestScreen: {
screen: ContinueAsGuestScreen
},
});
Related
I'm trying to import a component into my App.js class but when I try I get the error in my android emulator
invariant violation element type is invalid: expected a string or a class/function but got undefined you likely forgot to export your component from the file its defined in, or you might have mixed up default and named imports
check the render method of 'login'
my problem is that I checked that i'm importing a default import of the login component in my App.js and I am exporting the Login component correctly from what I can tell:
import React, {Component} from 'react';
import {StyleSheet,ScrollView,View,Text,Input,Button,SecureTextEntry,ActivityIndicator} from 'react-native';
import * as firebase from 'firebase';
import auth from '#react-native-firebase/auth';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
export default class Login extends Component {
state={
email: '',
password: '',
authenticating: false
};
componentDidMount(){
const firebaseConfig = {
apiKey: 'garbagekey',
authDomain: 'garbage auth domain'
}
firebase.initializeApp(firebaseConfig)
}
onButtonPress = () =>{
console.log("button pressed")
this.setState({authenticating:true})
}
contentBoolRender = () =>{
if(this.state.authenticating===true){
return(
<View>
<ActivityIndicator size="large"/>
</View>
)
}
return(
<View>
<Input
placeholder="Enter your Email..."
label = "Email"
onChangeText = {email => this.setState({email})}
value = {this.state.email}
/>
<Input
placeholder="Enter your Password..."
label = "Password"
onChangeText = {password => this.setState({password})}
value = {this.state.password}
SecureTextEntry
/>
<Button title="login" onpress={()=>this.onButtonPress()}></Button>
</View>
)
}
render() {
return(
<View>
{this.contentBoolRender()}
</View>
);
}
}
const styles = StyleSheet.create({
login:{
padding: 20,
backgroundColor: 'white'
},
});
App.js
import React, {Component} from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
Button,
} from 'react-native';
import * as firebase from 'firebase';
import auth from '#react-native-firebase/auth';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import Notes from "./notes.js";
import CreateNote from "./createnote.js";
import Login from "./login.js";
class App extends Component {
state = {
loggedin: false,
notes: [
{
id: 1,
text: "mow the lawn",
author: "dean",
time: "10am"
},
{
id: 2,
text: "feed the dog",
author: "sam",
time: "2pm"
}
]
};
componentDidMount(){
const firebaseConfig = {
apiKey: 'AIzaSyABmRXh2nlBt4FtjfOWNaoz7q5Wy5pGFlc',
authDomain: 'familytodo-28018.firebaseapp.com'
}
firebase.initializeApp(firebaseConfig)
}
confirmLogin=()=>{
this.setState({loggedin:true})
}
updateNotes = (title, name, eventTime) => {
console.log("making new note");
let newNote = {
text: title,
author: name,
time: eventTime
};
this.setState(state => {
const list = state.notes.concat(newNote);
console.log(list);
return {
notes: list
};
});
};
deleteNotes = note => {
console.log("note deleted", note.id);
this.setState(state => {
var list = this.state.notes;
for (let i = 0; i < this.state.notes.length; i++) {
if (this.state.notes[i].id === note.id) {
list.pop(i);
}
}
return {
notes: list
};
});
};
conditionalRender=()=>{
if(this.state.loggedin===false){
return (
<View>
<Login confirmlogin = {this.confirmLogin} />
</View>
)
}
return(
<View>
<CreateNote
handleName={this.handleName}
handleEvent={this.handleEvent}
handleTime={this.handleTime}
updateNotes={this.updateNotes}
/>
<Notes style={styles.notes} notes={this.state.notes} deleteNotes={this.deleteNotes} />
</View>
);
}
render() {
return(
<View>
{this.conditionalRender()}
</View>
);
}
}
const styles = StyleSheet.create({
app: {
marginHorizontal: "auto",
maxWidth: 500
},
logo: {
height: 80
},
header: {
padding: 20
},
title: {
fontWeight: "bold",
fontSize: 15,
marginVertical: 10,
textAlign: "center"
},
notes:{
marginHorizontal: '50%'
},
text: {
lineHeight: 15,
fontSize: 11,
marginVertical: 11,
textAlign: "center"
},
link: {
color: "#1B95E0"
},
code: {
fontFamily: "monospace, monospace"
}
});
export default App;
any help would be appreciate greatly please help me provide better info if possible :)
I think this is happening because react-native has no exported member named Input. I think you are looking for either TextInput (from react-native) or Input (from react-native-elements which has a label prop)
For the TextInput, try changing the login component to this:
import React, {Component} from 'react';
import {ActivityIndicator, Button, TextInput, View} from 'react-native';
import * as firebase from 'firebase';
export default class Login extends Component {
state = {
email: '',
password: '',
authenticating: false
};
componentDidMount() {
const firebaseConfig = {
apiKey: 'garbagekey',
authDomain: 'garbage auth domain'
};
firebase.initializeApp(firebaseConfig);
}
onButtonPress = () => {
console.log("button pressed");
this.setState({authenticating: true});
};
contentBoolRender = () => {
if (this.state.authenticating === true) {
return (
<View>
<ActivityIndicator size="large"/>
</View>
);
}
return (
<View>
<TextInput
placeholder="Enter your Email..."
onChangeText={email => this.setState({email})}
value={this.state.email}
/>
<TextInput
placeholder="Enter your Password..."
onChangeText={password => this.setState({password})}
value={this.state.password}
secureTextEntry
/>
<Button title="login" onPress={() => this.onButtonPress()}/>
</View>
);
};
render() {
return (
<View>
{this.contentBoolRender()}
</View>
);
}
}
or for Input try using this:
import React, {Component} from 'react';
import {ActivityIndicator, Button, View} from 'react-native';
import { Input } from 'react-native-elements';
import * as firebase from 'firebase';
export default class Login extends Component {
state = {
email: '',
password: '',
authenticating: false
};
componentDidMount() {
const firebaseConfig = {
apiKey: 'garbagekey',
authDomain: 'garbage auth domain'
};
firebase.initializeApp(firebaseConfig);
}
onButtonPress = () => {
console.log("button pressed");
this.setState({authenticating: true});
};
contentBoolRender = () => {
if (this.state.authenticating === true) {
return (
<View>
<ActivityIndicator size="large"/>
</View>
);
}
return (
<View>
<Input
placeholder="Enter your Email..."
label = "Email"
onChangeText={email => this.setState({email})}
value={this.state.email}
/>
<Input
placeholder="Enter your Password..."
label = "Password"
onChangeText={password => this.setState({password})}
value={this.state.password}
secureTextEntry
/>
<Button title="login" onPress={() => this.onButtonPress()}/>
</View>
);
};
render() {
return (
<View>
{this.contentBoolRender()}
</View>
);
}
}
Additionally, have a look through the code above as your Login component had a few other typos including: secureTextEntry and onPress
I'm new to react-native and am trying to use the Redux framework, I've encountered this problem: (The component for route ' ' must be a React component):
Thank you in advance.
Screen Error
Index.js
import React from 'react'
import { Provider } from 'react-redux'
import { AppRegistry } from 'react-native';
import { name as appName } from './app.json';
import Menu from './app/componnts/Menu'
import storeConfig from './app/store/storeConfig'
const store = storeConfig()
const Redux = () => {
return (
<Provider store={store}>
<Menu />
</Provider>
)
}
AppRegistry.registerComponent(appName, () => Redux);
Menu.js
import React, { Component } from 'react'
import {
StyleSheet,
SafeAreaView,
ScrollView,
Dimensions,
View,
Image,
Text
} from 'react-native'
import { createDrawerNavigator, DrawerItems, } from 'react-navigation'
import Login from './Login/Login'
import Viatura from './Viatura/Viatura'
export default class App extends Component {
render() {
return (
<AppDrawerNavigator />
)
}
}
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const AppDrawerNavigator = createDrawerNavigator({
Login,
Viatura,
}, {
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
})
Login.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { loginStore } from '../../store/actions/user.js';
import { Text, View, ImageBackground, Dimensions, Image, TextInput, TouchableOpacity, Alert } from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome'
import axios from 'axios'
import { createIconSetFromIcoMoon } from 'react-native-vector-icons'
import { API_MOTORISTAS_LOGIN } from '../../config'
import icoMoonConfig from '../../resources/fonts/selection.json'
import styles from './styles'
import bgImage from '../../images/fundo-vertical-preto.jpg'
import logo from '../../images/logo-tg-v-01.png'
const MyIcon = createIconSetFromIcoMoon(icoMoonConfig, 'icomoon', 'icomoon.ttf');
class Login extends Component {
constructor(props) {
super(props)
this.state = {
user: '',
password: '',
}
this.loginUser = this.loginUser.bind(this)
}
loginUser = () => {
try {
const { user, password } = this.state
this.setState({ error: '', })
axios.post(`${API_MOTORISTAS_LOGIN}`,
{
'param1': this.state.user,
'param2': this.state.password
}, {
"headers": {
'Content-Type': 'application/json',
}
}).then((response) => {
if (response.data.error) {
Alert.alert((response.data.error));
} else {
this.props.onLogin({ ...this.state })
const api_token = response.data.api_token
this.props.navigation.navigate('Viatura', {
api_token: api_token,
})
}
})
.catch((error) => {
console.log("axios error:", error);
});
} catch (err) {
Alert.alert((err))
}
}
static navigationOptions = {
drawerIcon: ({ tintColor }) => (
<MyIcon name="fonte-tg-33" style={{ fontSize: 24, color: tintColor }} />
)
}
render() {
return (
<ImageBackground
source={bgImage}
style={styles.backgroundContainer}>
<View
style={{
height: (Dimensions.get('window').height / 10) * 10,
alignItems: 'center',
justifyContent: 'center',
}}>
<View style={styles.logoContainer}>
<Image source={logo} style={styles.logo} />
</View>
<View style={styles.inputText}>
<View style={styles.iconContainer}>
<MyIcon style={styles.icon} name="fonte-tg-39" size={25} />
</View>
<TextInput
style={styles.input}
placeholder={'User'}
placeholderTextColor={'rgba(0, 0, 0, 0.6)'}
underlineColorAndroid='transparent'
value={this.state.user}
onChangeText={user => this.setState({ user })}
/>
</View>
<View style={styles.inputText}>
<View style={styles.iconContainer}>
<MyIcon style={styles.icon} name="fonte-tg-73" size={25} />
</View>
<TextInput
style={styles.input}
placeholder={'Password'}
secureTextEntry={true}
placeholderTextColor={'rgba(0, 0, 0, 0.6)'}
underlineColorAndroid='transparent'
value={this.state.password}
onChangeText={password => this.setState({ password })}
/>
</View>
<View style={styles.buttonsLogin}>
<TouchableOpacity style={styles.btnSair}>
<Text style={styles.text}> Sair </Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.loginUser} style={styles.btnEntrar}>
<Text style={styles.text}> Entrar </Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
)
}
}
const mapDispatchToProps = dispatch => {
return {
onLogin: user => dispatch(loginStore(user))
}
}
export default connect(null, mapDispatchToProps)(Login);
actionTypes.js
export const USER_LOGGED_IN = 'USER_LOGGED_IN';
export const USER_LOGGED_OUT = 'USER_LOGGED_OUT';
user.js (inside actions folder)
import { USER_LOGGED_IN, USER_LOGGED_OUT } from './actionTypes'
export const login = user => {
return {
type: USER_LOGGED_IN,
payload: user
}
}
export const logout = () => {
return {
type: USER_LOGGED_OUT,
}
}
user.js (inside reducers folder)
import { USER_LOGGED_IN, USER_LOGGED_OUT } from '../actions/actionTypes'
const initalState = {
user: null,
password: null
}
const reducer = (state = initalState, action) => {
switch (action.type) {
case USER_LOGGED_IN:
return {
...state,
user: action.paypload.user,
password: action.paypload.password
}
case USER_LOGGED_OUT:
return {
...state,
user: null,
password: null,
}
default:
return state
}
}
export default reducer
storeConfig.js
import { createStore, combineReducers } from 'redux'
import userReducer from './reducers/user'
const reducers = combineReducers({
user: userReducer,
})
const storeConfig = () => {
return createStore(reducers)
}
export default storeConfig
As I said at the beginning of the post, I'm still a beginner at react-native, so I'm posting several snippets of code so that I can be as clear as possible about how my situation is.
I don't think your screen is properly setting export default.
can you change this code?
import React, { Component } from 'react'
import {
StyleSheet,
SafeAreaView,
ScrollView,
Dimensions,
View,
Image,
Text
} from 'react-native'
import { createDrawerNavigator, DrawerItems, } from 'react-navigation'
import Login from './Login/Login'
import Viatura from './Viatura/Viatura'
export default class App extends Component {
render() {
return (
<AppDrawerNavigator />
)
}
}
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{ flex: 1 }}>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const AppDrawerNavigator = createDrawerNavigator(
{
Login : () => <Login />,
Viatura : () => <Viatura />
},
{
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
}
)
OR
import { Login } from './Login/Login'
import { Viatura } from './Viatura/Viatura'
...
const AppDrawerNavigator = createDrawerNavigator(
{
Login : { screen: Login },
Viatura : { screen: Viatura }
},
{
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
}
)
Try this
const AppDrawerNavigator = createDrawerNavigator({
Login:Login,
Viatura:Login,
}, {
contentComponent: CustomDrawerComponent,
drawerWidth: 300,
contentOptions: {
activeTintColor: 'orange'
}
})
I don't know why I can't import my screen, or I just can't find my mistake. I have another screen like this one. The import and the stack navigator screens is like here, but there isn't error there.
Here is my code:
import React, {Component} from 'react';
import * as firebase from 'firebase';
import {Container, Content, Header, Text, Form, Input, Item, Button} from 'native-base';
import Icon from 'react-native-vector-icons/Ionicons';
import {createAppContainer, createStackNavigator} from 'react-navigation';
import {StyleSheet, ImageBackground, Dimensions, Image, View} from 'react-native';
import MainNavigator from './LoginScreen';
// Some Code
const MainNavigator1 = createStackNavigator({
SignUp: {
screen: SignUpScreen,
navigationOptions: {
header: null,
}
},
Login: {
screen: MainNavigator,
navigationOptions: {
header: null,
}
}
})
export default createAppContainer(MainNavigator1);
const styles = StyleSheet.create ({
container:{
flex: 1,
backgroundColor: null,
justifyContent: 'center',
padding: 10
},
profileImg: {
height: 80,
width: 80,
overflow: 'hidden',
}
})
LogInScreen:
import React, {Component} from 'react';
import * as firebase from 'firebase';
import {Container, Content, Header, Text, Form, Input, Item, Button} from 'native-base';
import Icon from 'react-native-vector-icons/Ionicons';
import {createAppContainer, createStackNavigator} from 'react-navigation';
import {StyleSheet, ImageBackground, Dimensions, Image, View} from 'react-native';
import AppContainer22 from './DrawerNavigatorNew';
import MainNavigator1 from './SignUpScreen';
const firebaseConfig = {
apiKey:
authDomain:
databaseURL:
projectId:
storageBucket:
};
firebase.initializeApp(firebaseConfig);
class LoginScreen extends React.Component {
constructor (props) {
super(props)
this.state =({
email:'',
password:'',
error:'',
})
}
/*
signUpUser = (email, password) => {
try {
if(this.state.password.length <6)
{
alert("Please enter atleast 6 characters")
return;
}
firebase.auth().createUserWithEmailAndPassword(email, password)
}
catch (error){
console.log(error.toString())
}
}
*/
onSignInPress() {
this.setState({error:''})
const {email, password} = this.state;
firebase.auth().signInWithEmailAndPassword(email, password)
.then(() => {
this.setState({error:''})
this.props.navigation.navigate('Drawer');
})
.catch(() => {
this.setState({error:'Authentication failed'})
})
}
render(){
let { height, width } = Dimensions.get('window');
return (
<ImageBackground source={{uri:'https://guidetoiceland.is/image/437199/x/0/northern-lights-in-all-the-colors-of-the-rainbow-dance-across-the-sky-in-iceland-6.jpg'}}
style={{height, width}}>
<Container style={styles.container}>
<View style={{justifyContent:'center', alignItems:'center'}}>
<Image source={{uri:'https://image.flaticon.com/icons/png/512/10/10155.png'}}
style={styles.profileImg}/>
</View>
<Form>
<Item rounded>
<Icon active name='md-mail' size={20} color={'white'}/>
<Input
name='email'
placeholder='YourEmail#gmail.com'
autoCorrect={false}
autoCapitalize='none'
onChangeText={(email)=> this.setState({email})}
keyboardType='email-address'
style={{marginTop: 10}}
/>
</Item>
<Item rounded>
<Icon active name='md-key' size={25} color={'white'}/>
<Input
name='password'
placeholder='******'
secureTextEntry={true}
autoCorrect={false}
autoCapitalize='none'
onChangeText={(password)=> this.setState({password})}
style={{marginTop: 10}}
/>
</Item>
<Text style={{color: 'red'}}>{this.state.error}</Text>
<Button style={{marginTop: 10}}
full
rounded
success
onPress = {this.onSignInPress.bind(this)}
>
<Text> Login </Text>
</Button>
<Button style={{marginTop: 10}}
full
rounded
primary
onPress = {this.props.navigation.navigate('SignUp')}
>
<Text style={{color: 'white' }}> Sign Up </Text>
</Button>
</Form>
</Container>
</ImageBackground>
);
}
}
const MainNavigator = createStackNavigator({
Home: {
screen: LoginScreen,
navigationOptions: {
header: null,
}
},
Drawer: {
screen: AppContainer22,
navigationOptions: {
header: null,
}
},
SignUp: {
screen: MainNavigator1,
navigationOptions: {
header: null,
}
}
});
export default createAppContainer(MainNavigator);
const styles = StyleSheet.create ({
container:{
flex: 1,
backgroundColor: null,
justifyContent: 'center',
padding: 10
},
profileImg: {
height: 80,
width: 80,
overflow: 'hidden',
}
})
And here is the Error:
how to navigate from LoginForm.js to product.js ?
route.js
import React from 'react';
import { StyleSheet,View,Text } from 'react-native';
import { StackNavigator } from 'react-navigation';
import Home from './pages/home';
import Products from './pages/product';
// import Products from './pages/components/LoginForm';
const navigation = StackNavigator({
Home : { screen: Home },
// Login : { screen: LoginForm },
Products : { screen: Products },
});
export default navigation;
home.js
import React from 'react';
import { StyleSheet, Text, View, Button, StatusBar, Image } from 'react-native';
import LoginForm from './components/LoginForm';
export default class Home extends React.Component {
static navigationOptions = {
header: null
};
render() {
return (
<View style = { styles.container }>
<StatusBar
backgroundColor="#007ac1" barStyle="light-content"/>
<View style= { styles.logoContainer }>
<Image style = {styles.logo} source={require('../images/logo.png')} />
</View>
<View style= { styles.formContainer }>
<LoginForm />
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#03a9f4'
},
logoContainer: {
flexGrow: 1, justifyContent:'center', alignItems:'center'
},
logo: {
width: 80, height: 80
},
formContainer: {
}
});
LoginForm.js
import React from 'react';
import { StyleSheet, Text, View ,TextInput, TouchableOpacity } from 'react-native';
export default class LoginForm extends React.Component {
constructor(props){
super(props)
this.state={
userName:'',
password:'',
type:'A'
}
}
userLogin = () =>{
const { userName } = this.state;
const { password } = this.state;
const { type } = this.state;
fetch('http://192.168.0.4:3000/notes',{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body:JSON.stringify({
userName : userName,
password : password,
type : type
})
})
.then((response)=> response.json())
.then((responseJson) => {
if(responseJson.response.success == true) {
// alert(responseJson.response.result);
navigate('Products');
}else{
alert(responseJson.response.result);
}
})
.catch((error)=>{
console.error(error);
})
}
render() {
return (
<View style = {styles.container}>
<TextInput
underlineColorAndroid="transparent"
placeholder="Username or Email"
placeholderTextColor = "rgba(255,255,255,0.7)"
returnKeyType="next"
onSubmitEditing={() => this.passwordInput.focus()}
onChangeText = {userName => this.setState({userName})}
style={styles.input} />
<TextInput
placeholder="Password"
underlineColorAndroid="transparent"
secureTextEntry
returnKeyType="go"
placeholderTextColor = "rgba(255,255,255,0.7)"
ref = {(input) => this.passwordInput = input}
onChangeText = {password => this.setState({password})}
style={styles.input} />
<TouchableOpacity style={styles.buttonContainer} onPress={this.userLogin} >
<Text style={styles.buttonText}>LOGIN</Text>
</TouchableOpacity>
</View>
)
}
}
const styles = StyleSheet.create({
container : {
padding:20
},
input: {
height:40, backgroundColor: 'rgba(255,255,255,0.2)', marginBottom:20,
color:'#FFF', paddingHorizontal:10, borderRadius:5
},
buttonContainer: {
backgroundColor: "#2980b9", paddingVertical:10, borderRadius:5
},
buttonText: {
textAlign :'center', color:'#FFFFFF', fontWeight:'700'
}
});
product.js
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default class Product extends React.Component {
static navigationOptions = {
// title: 'Home',
header: null
};
render() {
return (
<View style = { styles.container }>
<Text> Product Page open </Text>
<Button
title="Go to Home"
onPress={() => this.props.navigation.navigate('Home')}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Make LoginForm as part of navigator (it is currently commented). Then inside the userLogin function use this.props.navigation.navigate('Products') to navigate, take a look at the navigation doc
userLogin = () =>{
...
fetch('http://192.168.0.4:3000/notes',{
...
})
.then((response)=> response.json())
.then((responseJson) => {
if(responseJson.response.success == true) {
// alert(responseJson.response.result);
this.props.navigation.navigate('Products');
}else{
alert(responseJson.response.result);
}
})
.catch((error)=>{
console.error(error);
})
}
Hope this will help!
I have consulted every question in StackOverflow regarding this problem with no success. I continuously get the following error `Route 'Home' should declare a screen.
This error seems to indicate that I must import a component into my working file if I want to use it as a screen, is that the case? If so, Why? That's probably what's wrong with my code, otherwise, I'm not sure what is wrong here: I would like to understand why this isn't working, I have consulted multiple guides on the subject.
my index.android.js:
import './app/index.js'
my index.js (not in full):
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View, Button, Image, TextInput }
from 'react-native';
import { StackNavigator } from 'react-navigation';
const RallyMobileNavigator = StackNavigator({
Home: { screen: RallyMobile },
LogIn: { screen: LogIn }
},{
initialRouteName: 'Home'
});
class RallyMobile extends Component {
static navigationOptions = {
title: 'Welcome',
};
state = {
initialPosition: {},
lastPosition: {},
userData: [],
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
<Button
onPress={() => navigate('LogIn')}
title='Sign In'
/>
</View>
<View style={styles.EventListContainer}>
<EventList
location={this.state.lastPosition.location ?
this.state.lastPosition.location :
this.state.initialPosition.location}
/>
</View>
</View>
);
};
};
class LogIn extends Component {
state = {
userName: '',
password: ''
}
static navigationOptions = {
title: 'Sign In',
};
logInUser = () => {
console.log("test");
}
render() {
return(
<View>
<View style={{padding: 10}}>
<TextInput
style={{height: 40}}
placeholder="Username"
onChangeText={(text) => this.setState({userName})}
/>
<TextInput
style={{height: 40}}
placeholder="Password"
onChangeText={(text) => this.setState({password})}
/>
</View>
<View>
<button
onPress={logInUser()}
title='Sign In'
/>
</View>
</View>
)
}
}
AppRegistry.registerComponent('RallyMobile', () => RallyMobileNavigator);
Move
const RallyMobileNavigator = StackNavigator({
Home: { screen: RallyMobile },
LogIn: { screen: LogIn }
},{
initialRouteName: 'Home'
});
To just above
AppRegistry.registerComponent('RallyMobile', () => RallyMobileNavigator);
Credit:
https://github.com/react-community/react-navigation/issues/571#issuecomment-284207331