React Native - Error when i want to navigate - android

I have an error when i try to navigate using react.navigation.
I also have a visual bug since i've added react navigation.
Here's my code for app.js :
import React, { useState } from "react";
import {
StyleSheet,
Text,
View,
Image,
TextInput,
Button,
TouchableOpacity,
} from "react-native";
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import HomeScreen from './HomeScreen';
import RegisterScreen from './RegisterScreen';
const Stack = createNativeStackNavigator();
export default function App() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const link = "./Ressources/logoressources.png";
/*async function ClickLogin(){
alert(email);
l
}
async function ClickRegister(){
alert(email);
}
async function ClickMotDePasseOublie(){
alert("Fallait pas l'oublier (Veuillez l'ecrire sur un papier que vous nous remettrez la prochaine fois)");
}*/
//<Stack.Navigator>
/* <Stack.Screen
name="Home"
component={HomeScreen}
/>*/
//</Stack.Navigator>
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false
}}>
<Stack.Screen
name="Home"
component={HomeScreen}
/>
<Stack.Screen
name="Register"
component={RegisterScreen}
/>
</Stack.Navigator>
<HomeScreen />
</NavigationContainer>
);
}
Here the code of the HomePage.js :
import React, { useState } from "react";
import RegisterScreen from './RegisterScreen';
import {
StyleSheet,
Text,
View,
Image,
TextInput,
Button,
TouchableOpacity,
} from "react-native";
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
//import HomeScreen from './HomeScreen';
const Stack = createNativeStackNavigator();
const HomeScreen = ({navigation}) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const link = "./Ressources/logoressources.png";
async function ClickLogin(){
alert(email);
}
async function ClickRegister(){
navigation.navigate("Register");
}
async function ClickMotDePasseOublie(){
alert("Fallait pas l'oublier (Veuillez l'ecrire sur un papier que vous nous remettrez la prochaine fois)");
}
//<Stack.Navigator>
/* <Stack.Screen
name="Home"
component={HomeScreen}
/>*/
//</Stack.Navigator>
return (
<View style={styles.container}>
<Image style={styles.image} source={require(link)} />
<View style={styles.inputView}>
<TextInput
style={styles.TextInput}
placeholder="Email"
placeholderTextColor="#003f5c"
onChangeText={(email) => setEmail(email)}
/>
</View>
<View style={styles.inputView}>
<TextInput
style={styles.TextInput}
placeholder="Mot de passe"
placeholderTextColor="#003f5c"
secureTextEntry={true}
onChangeText={(password) => setPassword(password)}
/>
</View>
<View style={styles.inputViewConfirm}>
<TextInput
style={styles.TextInput}
placeholder="Confirmer mot de passe"
placeholderTextColor="#003f5c"
secureTextEntry={true}
onChangeText={(password) => setPassword(password)}
/>
</View>
<TouchableOpacity onPress={ClickMotDePasseOublie}>
<Text style={styles.forgot_button}>Mot de passe oubliƩ ?</Text>
</TouchableOpacity>
<TouchableOpacity onPress={ClickRegister}>
<Text style={styles.Register_button}>Pas de compte ? Inscrivez-vous !</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.loginBtn}
onPress={ClickLogin}>
<Text style={styles.loginText}>Se connecter</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#16a085",
alignItems: "center",
justifyContent: "center",
},
image: {
marginBottom: 10,
height: 200,
},
inputView: {
backgroundColor: "#A6E4E7",
borderRadius: 30,
width: "75%",
height: 45,
marginBottom: 20,
alignItems: "center",
},
inputViewConfirm: {
backgroundColor: "#A6E4E7",
borderRadius: 30,
width: "75%",
height: 45,
marginBottom: 20,
alignItems: "center",
},
TextInput: {
height: 50,
flex: 1,
marginLeft: 10,
},
forgot_button: {
height: 30,
marginBottom: 20,
},
Register_button: {
color: "#4834d4",
height: 30,
marginBottom: 10,
},
loginBtn: {
width: "80%",
borderRadius: 25,
height: 50,
alignItems: "center",
justifyContent: "center",
marginTop: 5,
backgroundColor: "#88FFDD",
},
});
export default HomeScreen;
And the registerScreen Code :
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
const RegisterScreen = ({navigation}) => {
return (
<View style={styles.container}>
<Text>Add friends here!</Text>
</View>
);
}
// ...
export default RegisterScreen;
This is my error :
And now a screenshot of the render of the application :
Do you have a solution for me ?
I Have tryed to remove the top navigation bar to realign the interface but nothing worked.
I also verified my routes for the redirection bug, already searched answers on the internet and in the documentation but nothing got found.

Promise Unhandled Promise Rejection is usually an error from a function and not from your navigation.
From the code you provided, this error might be coming from your alert function.
If your function "alert" is really a promise (I see that you used the "async" word), you should use "await" before the function call:
await alert()
Also, remember to use try/catch when creating the function.
This way you'll be able to catch and console the error to better understand where it comes from.
async function alert() {
try {
// do some async work
await doSomething()
} catch (error) {
// understand error
console.log(error)
// handle error
}
}

Related

I am facing a very mysterious problem while sending data to the Firebase database

I'm making a simple chat application with React native and Firebase. But I could not manage to send the data I wanted to add to the database with the sendMessage function. I am getting an error like this and could not find the solution. Can you help me? I couldn't find where addDoc () belongs and also I don't know what SyntheticObject means. I am having such a problem, although I do not exactly comply with what was said in the tutorial video I followed the project.
Error image:
https://i.resmim.net/i/WhatsApp-Image-2021-05-25-at-21.34.11.jpeg
Error: Function addDoc() invalid data.
import React, {useLayoutEffect, useState} from 'react'
import { TouchableOpacity } from 'react-native';
import { StyleSheet, Text, View } from 'react-native'
import {Avatar} from "react-native-elements";
import {AntDesign, FontAwesome, Ionicons} from "#expo/vector-icons";
import { SafeAreaView } from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { KeyboardAvoidingView, TextInput } from 'react-native';
import { Platform } from 'react-native';
import { ScrollView } from 'react-native';
import { Keyboard } from 'react-native';
import { TouchableWithoutFeedback } from 'react-native';
import { db, auth } from '../firebase';
import * as firebase from "firebase";
const ChatScreen = ({ navigation, route }) => {
const [input, setInput] = useState("");
useLayoutEffect(() => {
navigation.setOptions({
title: "Chat",
headerBackTitleVisible: false,
headerTitleAlign: "left",
headerTitle: () => (
<View
style={{
flexDirection: "row",
alignItems: "center",
}}>
<Avatar rounded source={{uri: "https://cencup.com/wp-content/uploads/2019/07/avatar-placeholder.png",}} />
<Text
style={{color: "white", marginLeft: 10, fontWeight: "700"}}
>{route.params.chatName}</Text>
</View>
),
headerLeft: () => (
<TouchableOpacity
style={{marginLeft: 10}}
onPress={navigation.goBack}
>
<AntDesign name="arrowleft" size={24} color="white" />
</TouchableOpacity>
),
headerRight: () => (
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
width: 80,
marginRight: 20,
}}>
<TouchableOpacity>
<FontAwesome name="video-camera" size={24} color="white" />
</TouchableOpacity>
<TouchableOpacity>
<Ionicons name="call" size={24} color="white" />
</TouchableOpacity>
</View>
)
});
}, [navigation]);
const sendMessage = () => {
Keyboard.dismiss();
db.collection('chats').doc(route.params.id).collection('messages').add({
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
message: input,
displayName: auth.currentUser.displayName,
email: auth.currentUser.email,
photoURL: auth.currentUser.photoURL
})
setInput('')
};
return (
<SafeAreaView style={{ flex: 1, backgroundColor: "white"}}>
<StatusBar style="light" />
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container}
keyboardVerticalOffset={90}>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<>
<ScrollView>
</ScrollView>
<View style={styles.footer}>
<TextInput
placeholder="Signal Message"
value={input}
onChange={text => setInput(text)}
onSubmitEditing={sendMessage}
style={styles.textInput}/>
<TouchableOpacity onPress={sendMessage} activeOpacity={0.5}>
<Ionicons name="send" size={24} color="#2B68E6" />
</TouchableOpacity>
</View>
</>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
export default ChatScreen
const styles = StyleSheet.create({
container: {
flex:1,
},
footer: {
flexDirection: "row",
alignItems: "center",
width: "100%",
padding: 15,
},
textInput:{
bottom: 0,
height: 40,
flex: 1,
marginRight: 15,
backgroundColor: "#ECECEC",
padding: 10,
color: "grey",
borderRadius: 30,
},
})
Error image:
https://i.resmim.net/i/WhatsApp-Image-2021-05-25-at-21.34.11.jpeg
onChange={text => setInput(text)}
While you've called the parameter "text", it's actually an event object, specifically a "SyntheticEvent" (these are event objects used by react). So later when you try to send that to the database, firebase says, basically, "uh, i can't serialize this".
Instead, you may want to use the onChangeText event:
onChangeText={text => setInput(text)}
Your onChange function should be like this
onChange={e => setInput(e.nativeEvent.text)}
You're sending the event object not the text
You could also use onChangeText prop instead
onChangeText={text => setInput(text)}

Navigation from Login screen to Drawer.Navigator first screen Not able to navigate from one screen to drawer navigation

I am very new to react native and this is my 1st application my org has given me to do a PoC for the same.
My requirement is i have to develop an app with
Login screen -----> Navigation Drawer(1) screen Name-- workProcessor and 2) Operation Analytics)
I am able to achieve screen at 2 different level's
i.e i am able to design Login screen and i am able to design workprocessor and operation analytics screen and switch between them
I am not able to Integrate my login screen and on click of login i should navigate to Navigation-drawer screen
My files are :
Login.js
import React from 'react';
import {
ScrollView,
Text,
TextInput,
View,
Button,
StyleSheet
} from 'react-native';
import Logo from './Logo';
import Form from './Form';
export default class Login extends React.Component {
render() {
return (
<View style={styles.container}>
<Logo></Logo>
<Form type = "Login"></Form>
<View style ={styles.workSpaceText}>
<Text style = {styles.workSpaceText}> Change WorkSpace ?</Text>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#455a64',
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
workSpaceText: {
flexGrow:1,
justifyContent:'center',
alignItems:'center',
},
workSpaceText: {
fontSize: 15,
marginVertical:15,
color: 'rgba(255,255,255,0.7)'
}
});
Form.js
import React from 'react';
import { StyleSheet, TextInput, View, Image, TouchableOpacity, Text } from "react-native";
import { useNavigation } from '#react-navigation/native';
// import { Actions } from 'react-native-router-flux';
const Form = () => {
const navigation = useNavigation();
loginMove= ()=>{
navigation.navigate('Landing');
}
return (
<View style={styles.container}>
<TextInput style={styles.inputBox}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Username"
placeholderTextColor='#ffffff'
/>
<TextInput style={styles.inputBox}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Password"
placeholderTextColor='#ffffff'
/>
<TouchableOpacity style={styles.button} onPress={loginMove}>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
</View>
);
}
export default Form;
const styles = StyleSheet.create({
container: {
flexGrow: 1,
justifyContent: 'center',
alignItems: 'center'
},
inputBox: {
width: 300,
backgroundColor: 'rgba(255,255,255,0.5)',
borderRadius: 25,
paddingHorizontal: 16,
fontSize: 16,
color: '#ffffff',
marginVertical: 10
},
button: {
width: 300,
backgroundColor: '#1c313a',
borderRadius: 25,
marginVertical: 20,
paddingVertical: 12
},
buttonText: {
fontSize: 16,
fontWeight: '500',
color: '#ffffff',
textAlign: 'center'
}
});
And my Drawer File
i.e LandingScreen.js
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* #format
* #flow strict-local
*/
import React from 'react';
// import { Router, Stack, Scene } from 'react-native-router-flux';
import 'react-native-gesture-handler';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { createDrawerNavigator } from '#react-navigation/drawer';
import WorkProcessor from './workprocessor';
import OperationAnalytics from './OperationAnalytics';
import { Button, View, Text, TouchableOpacity, Image } from 'react-native';
const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();
const NavigationDrawerStructure = (props) => {
//Structure for the navigatin Drawer
const toggleDrawer = () => {
//Props to open/close the drawer
props.navigationProps.toggleDrawer();
};
return (
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity onPress={() => toggleDrawer()}>
{/*Donute Button Image */}
<Image
source={{ uri: 'https://raw.githubusercontent.com/AboutReact/sampleresource/master/drawerWhite.png' }}
style={{ width: 25, height: 25, marginLeft: 5 }}
/>
</TouchableOpacity>
</View>
);
}
function firstScreenStack({ navigation }) {
return (
<Stack.Navigator initialRouteName="FirstPage">
<Stack.Screen
name="FirstPage"
component={WorkProcessor}
options={{
title: 'Work-Processor', //Set Header Title
headerLeft: () => <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#f4511e', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}
/>
</Stack.Navigator>
);
}
function secondScreenStack({ navigation }) {
return (
<Stack.Navigator
initialRouteName="SecondPage"
screenOptions={{
headerLeft: () => <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#f4511e', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
}
}}>
<Stack.Screen
name="SecondPage"
component={OperationAnalytics}
options={{
title: 'Operational Analytics', //Set Header Title
}} />
</Stack.Navigator>
);
}
const LandingScreen = () => (
<NavigationContainer>
<Drawer.Navigator
drawerContentOptions={{
activeTintColor: '#e91e63',
itemStyle: { marginVertical: 5 },
}}>
<Drawer.Screen
name="FirstPage"
options={{ drawerLabel: 'Work-Processor' }}
component={firstScreenStack} />
<Drawer.Screen
name="SecondPage"
options={{ drawerLabel: 'Operation-Analytics' }}
component={secondScreenStack} />
</Drawer.Navigator>
</NavigationContainer>
);
export default LandingScreen;
When i am clicking on login button i.e loginMove .. it is not moving to navigation drawer screen and giving error: -
Error: Looks like you have nested a 'NavigationContainer' inside another. Normally you need only one container at the root of the app, so this was probably an error. If this was intentional, pass 'independent={true}' explicitely. Note that this will make the child navigators disconnected from the parent and you won't be able to navigate between them.
Please can some one help me completing this flow. I am ready for doing any code changes it's my PoC
You cannot embedd NavigationContainer, only stacks, drawers, tabs, etc
I suggest you to make two Navigations, one for login, one logged. This prevent to back to login screen when already logged in.
Example
// App.js
return(
<NavigationContainer>
{isLogged ? <LoggedNav /> : <LoginNav />}
</NavigationContainer>
)
With your Drawer in LoggedNav and Stacks in LoginNav
OR
In a first stack, you have a screen with your drawer stack and one with your landing page stack. You can embedd stacks as much as you want but not NavigationContainer. A screen can be a stack without problems.
function Login({ navigation }) {
return (
<Stack.Navigator initialRouteName="FirstPage">
<Stack.Screen
name="FirstPage"
component={WorkProcessor}
options={{
title: 'Work-Processor', //Set Header Title
headerLeft: () => <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#f4511e', //Set Header color
},
headerTintColor: '#fff', //Set Header text color
headerTitleStyle: {
fontWeight: 'bold', //Set Header text style
},
}}
/>
</Stack.Navigator>
);
}
const LandingScreen = () => (
<Drawer.Navigator
drawerContentOptions={{
activeTintColor: '#e91e63',
itemStyle: { marginVertical: 5 },
}}>
<Drawer.Screen
name="FirstPage"
options={{ drawerLabel: 'Work-Processor' }}
component={firstScreenStack} />
<Drawer.Screen
name="SecondPage"
options={{ drawerLabel: 'Operation-Analytics' }}
component={secondScreenStack} />
</Drawer.Navigator>
);
return(
<NavigationContainer>
<Stack.Navigator initialRouteName="login">
<Stack.Screen name="login" component={Login} ... />
<Stack.Screen name="landing" component={LandingScreen} ... />
</Stack.Navigator>
</NavigationContainer>
)

How do I program a button to open react navigation drawer in react native?

I am a noob at React Native and I am confused on how to program a floating button to open the react-native navigation drawer.
As of right now I am calling the button in MapScreen.js. The button is called FloatingButton.js.
I have running into the error of "ReferenceError: Can't Find variable: navigation" when I press the button.
A bit of preface, I have been using burger menus on headers to open the drawer menu.
App.js
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { createDrawerNavigator } from '#react-navigation/drawer';
import { StatusBar } from 'expo-status-bar';
import * as React from 'react';
import { StyleSheet, View, Image } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import useCachedResources from './hooks/useCachedResources';
//import BottomTabNavigator from './navigation/BottomTabNavigator';
//import LinkingConfiguration from './navigation/LinkingConfiguration';
import HomeScreen from './screens/HomeScreen';
import MapScreen from './screens/MapScreen';
import LinksScreen from './screens/LinksScreen';
//import FloatingButton from './components/FloatingButton';
const HomeStack = createStackNavigator();
const LinksStack = createStackNavigator();
const Drawer = createDrawerNavigator();
const HomeStackScreen = ({navigation}) => (
<HomeStack.Navigator screenOptions={{
headerStyle: {
backgroundColor: '#2a2a2a'
},
headerTintColor: '#fff'
}}>
<HomeStack.Screen name="Drive" component={HomeScreen} options={{
headerLeft: () => (
<Icon.Button name="ios-menu" size={25}
backgroundColor = "#2a2a2a" onPress={()=> navigation.openDrawer()}></Icon.Button>
)
}} />
</HomeStack.Navigator>
);
const LinkStackScreen = ({navigation}) => (
<LinksStack.Navigator screenOptions={{
headerStyle: {
backgroundColor: '#2a2a2a'
},
headerTintColor: '#fff'
}}>
<LinksStack.Screen name="Links" component={LinksScreen} options={{
headerLeft: () => (
<Icon.Button name="ios-menu" size={25}
backgroundColor = "#2a2a2a" onPress={()=> navigation.openDrawer()}></Icon.Button>
)
}} />
</LinksStack.Navigator>
);
export default function App(props) {
const isLoadingComplete = useCachedResources();
if (!isLoadingComplete) {
return null;
} else {
return (
<View style={styles.container}>
<NavigationContainer>
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={HomeStackScreen} />
<Drawer.Screen name="Drive" component={MapScreen} />
<Drawer.Screen name="Links" component={LinkStackScreen} />
</Drawer.Navigator>
</NavigationContainer>
<StatusBar style="auto" />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#242C40',
}
});
MapScreen.js
import React, {useState} from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import Maps from '../components/GoogleMaps';
import FloatingButton from '../components/FloatingButton';
export default class MapScreen extends React.Component {
render() {
return (
<View style={styles.container}>
<Maps
style={ styles.map }
/>
<FloatingButton style= {{bottom: 645, right: 380}} /> {/* broken button */}
</View>
);
}
}
function DevelopmentModeNotice() {
if (__DEV__) {
const learnMoreButton = (
<Text onPress={handleLearnMorePress} style={styles.helpLinkText}>
Learn more
</Text>
);
return (
<Text style={styles.developmentModeText}>
Development mode is enabled {learnMoreButton}
</Text>
);
} else {
return (
<Text style={styles.developmentModeText}>
You are not in development mode:
</Text>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#4B4B4B',
},
developmentModeText: {
marginBottom: 20,
color: '#BCBCBC',
fontSize: 14,
lineHeight: 19,
textAlign: 'center',
},
contentContainer: {
paddingTop: 30,
},
welcomeContainer: {
alignItems: 'center',
marginTop: 10,
marginBottom: 20,
},
welcomeImage: {
width: 100,
height: 80,
resizeMode: 'contain',
marginTop: 3,
marginLeft: -10,
},
getStartedContainer: {
alignItems: 'center',
marginHorizontal: 50,
},
homeScreenFilename: {
marginVertical: 7,
},
codeHighlightText: {
color: 'rgba(96,100,109, 0.8)',
},
codeHighlightContainer: {
backgroundColor: 'rgba(0,0,0,0.5)',
borderRadius: 3,
paddingHorizontal: 4,
},
getStartedText: {
fontSize: 17,
color: '#E2E2E2',
lineHeight: 24,
textAlign: 'center',
},
tabBarInfoContainer: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
...Platform.select({
ios: {
shadowColor: 'black',
shadowOffset: { width: 0, height: -3 },
shadowOpacity: 0.1,
shadowRadius: 3,
},
android: {
elevation: 20,
},
}),
alignItems: 'center',
backgroundColor: '#5F5F5F',
paddingVertical: 20,
},
tabBarInfoText: {
fontSize: 17,
color: '#E2E2E2',
textAlign: 'center',
},
navigationFilename: {
marginTop: 5,
},
helpContainer: {
marginTop: 15,
alignItems: 'center',
},
helpLink: {
paddingVertical: 15,
},
helpLinkText: {
fontSize: 14,
color: '#2e78b7',
},
map: {
height: '100%',
width: '100%',
}
});
FloatingButton.js I think this is where the problem lies, I think I am calling navigation wrong or
onPress={()=> navigation.openDrawer()} wrong.
import * as React from 'react';
import { StyleSheet, View, Text, Animated, TouchableWithoutFeedback } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import { createDrawerNavigator } from '#react-navigation/drawer';
import { NavigationContainer } from '#react-navigation/native';
const Drawer = createDrawerNavigator();
export default class FloatingButton extends React.Component ({navigation}) {
render() {
return (
<View style={[styles.container, this.props.style]}>
<TouchableWithoutFeedback onPress={()=> navigation.openDrawer()}>
<Animated.View style={[styles.button, styles.menu]}>
<Icon name="ios-menu" size={25} color = "#fff" />
</Animated.View>
</TouchableWithoutFeedback>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
alignItems: "center",
position: "absolute"
},
button: {
position:"absolute",
width: 45,
height: 45,
borderRadius: 60/2,
alignItems: "center",
justifyContent: "center",
shadowRadius: 10,
shadowColor: "#2a2a2a",
shadowOpacity: 0.3,
shadowOffset: {height: 10}
},
menu:{
backgroundColor:"#2a2a2a",
}
});
Here's what the MapScreen looks like
The error I get when I press the button
Drawer menu
Home screen
First option
In the map you can pass the navigation reference in a props like:
<FloatingButton
style= {{bottom: 645, right: 380}}
navigation={this.props.navigation}/>
then in your button component you can get the reference via the props and do:
this.props.navigation.openDrawer()
Second option
you can pass a callback to you component like:
<FloatingButton
style= {{bottom: 645, right: 380}}
isPressed={() => this.props.navigation.openDrawer()}/>
and call you callback like this in the button component
<TouchableWithoutFeedback onPress={()=> this.props.isPressed()}>
if your button is not in navigation stack, so you have not navigation as props then useNavigation is a good solution for you :
import { useNavigation } from '#react-navigation/native';
in your component:
const navigation = useNavigation();
then :
<TouchableOpacity onPress={() => navigation.openDrawer()}>
// your icon
</TouchableOpacity>

DrawerNavigator from another file is not working

I have following code in App.js
import React, { Component } from 'react';
import { Text, View,} from 'react-native';
import{DrawerNavigator, DrawerActions} from 'react-navigation';
import { Menu} from './src/components/menu';
export default class MainView extends Component {
render(){
return(
<View>
<Menu />
<Text> WHAT ??? </Text>
</View>
);
}
}
and following code in src/components/menu.js
'use strict';
import React, { Component } from 'react';
import { Text, View, StyleSheet, Image, ScrollView} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome5';
import{DrawerNavigator, DrawerActions} from 'react-navigation';
export class Menu extends Component {
render(){
return(
<View style= {styles.navContainer}>
<View style= {styles.navContainerFlexing}>
<View>
<Icon name="bars" size={25} color= 'black' style={{marginLeft: 10, fontWeight: '200' }} onPress={() => this.props.navigation.dispatch(DrawerActions.toggleDrawer())} />
</View>
<Text style={[styles.whiteText, styles.navItem]}>Home</Text>
</View>
</View>
);
}
}
export const Drawer = DrawerNavigator(
{
Menu: Menu,
},
{
// initialRouteName: 'Home',
},
{
drawerPosition: 'left',
initialRouteName: 'Home',
drawerBackgroundColor: 'white',
drawerWidth: 300,
}
);
const styles= StyleSheet.create({
navContainer: {
height: 55,
backgroundColor: '#3ba558',
alignItems: 'center',
// flex: 1,
flexDirection: 'row',
// justifyContent: 'flex-start'
},
navContainerFlexing: {
flex: 2,
flexDirection: 'row',
backgroundColor: '#3ba558',
paddingLeft: 20
},
whiteText: {
color: 'white',
},
navItem: {
alignItems: 'center',
marginTop: 'auto',
marginBottom: 'auto',
marginLeft: 10
},
});
Now I want my Menu class to display in App.js, which is displaying but and I also want it workable DrawerNavigator in homepage, right now the drawer is giving:
undefined is not an object (evaluating '_this.props.navigation.dispatch')
I Have explained the configuration of DrawerNavigator in the below link.
Look into the accepted answer in the below link.
How to create a Drawer Component and adding it to multiple screens
As I explained in it try to understand the concept and do not copy the syntax.
Do a comparison with your configuration, you will find your problem.

Open another screen in react-native

I have this screen in react native
import React, { Component } from 'react';
import { AppRegistry,TouchableOpacity, Text ,Button,Image,TextInput,PropTypes,StyleSheet,View,NavigatorIOS,TouchableHighlight} from 'react-native';
class LoginView extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>
HYGEX
</Text>
<View>
<TextInput
placeholder="Username"
style={styles.formInput}
/>
<TextInput
placeholder="Password"
secureTextEntry={true}
style={styles.formInput1}
/>
<TouchableHighlight style={styles.button}
onPress={() => this.move()}>
<Text style={styles.buttonText}>Login</Text>
</TouchableHighlight>
</View>
</View>
);
}
move() {
//what i can do here to go to Socrce screen ???
}
}
Something like login screen, now when I click into TouchableHighlight
I need to open this screen
'use strict';
import React, { Component } from 'react';
import { AppRegistry, ListView, Text, View } from 'react-native';
class HygexListView extends Component {
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows([
'John', 'Joel', 'James', 'Jimmy', 'Jackson', 'Jillian', 'Julie', 'Devin'
])
};
}
render() {
return (
<View style={{flex: 1, paddingTop: 22}}>
<ListView
dataSource={this.state.dataSource}
renderRow={(rowData) => <Text>{rowData}</Text>}
/>
</View>
);
}
}
module.exports = HygexListView;
I tried to implement move method but I failed! Any idea why?
Does react-native have a method to change the screen when click into TouchableHighlight?
As others pointed out, you have to use an instance of Navigator to transition between screens. Maybe you can have a look at the example apps in the React Native repo. I also find this router package quite easy to set up, and it also includes an example app that you can use as a starting point.
Edit
As a simple example using react-native-router-flux, you can edit the Example.js file in the Example directory to look like this:
import React, {
Component,
} from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
import LoginView from './LoginView';
import HygexListView from './HygexListView';
import {
Scene,
Router,
Actions,
} from 'react-native-router-flux';
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: 'transparent', justifyContent: 'center',
alignItems: 'center',
},
tabBarStyle: {
backgroundColor: '#eee',
},
tabBarSelectedItemStyle: {
backgroundColor: '#ddd',
},
});
// define this based on the styles/dimensions you use
const getSceneStyle = (/* NavigationSceneRendererProps */ props, computedProps) => {
const style = {
flex: 1,
backgroundColor: '#fff',
shadowColor: null,
shadowOffset: null,
shadowOpacity: null,
shadowRadius: null,
};
if (computedProps.isActive) {
style.marginTop = computedProps.hideNavBar ? 0 : 64;
style.marginBottom = computedProps.hideTabBar ? 0 : 50;
}
return style;
};
class Example extends Component {
render() {
return (
<Router getSceneStyle={getSceneStyle}>
<Scene key="login" component={LoginView} initial={true}/>
<Scene key="hygex" component={HygexListView } />
</Router>
);
}
}
export default Example;
Then, in your component's move function, you have to do the following:
move(){
Actions.hygex(); // This will perform a slide transition, but you can customize it. Have a look at the docs for that.
I have not tested the code, so there might be some typos/missing imports/code, but it should give you an idea of what you have to do.
}
You have to implement a Navigator, which is roughly a component that manages all stuff related to screens, and header bar with back button and etc.
As you are a beginner, I suggest you to look at the docs on this link:
https://facebook.github.io/react-native/docs/navigator.html
Sorry for the short answer, I'm on my phone.
Good luck!
"use strict";
var React = require("react-native");
var {
Component,
StyleSheet,
Text,
TextInput,
TouchableHighlight,
View,
} = React;
var SecureView = require("./SecureView");
class LoginView extends Component {
constructor(props) {
super(props);
this.state = {
username: "",
password: ""
};
}
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>
Sign In
</Text>
<View>
<TextInput
placeholder="Username"
onChange={(event) => this.setState({username: event.nativeEvent.text})}
style={styles.formInput}
value={this.state.username} />
<TextInput
placeholder="Password"
secureTextEntry={true}
onChange={(event) => this.setState({password: event.nativeEvent.text})}
style={styles.formInput}
value={this.state.password} />
<TouchableHighlight onPress={(this.onSubmitPressed.bind(this))} style={styles.button}>
<Text style={styles.buttonText}>Submit</Text>
</TouchableHighlight>
</View>
</View>
);
}
onSubmitPressed() {
this.props.navigator.push({
title: "Secure Page",
component: SecureView,
passProps: {username: this.state.username, password: this.state.password},
});
}
};
var styles = StyleSheet.create({
container: {
padding: 30,
marginTop: 65,
alignItems: "stretch"
},
title: {
fontSize: 18,
marginBottom: 10
},
formInput: {
height: 36,
padding: 10,
marginRight: 5,
marginBottom: 5,
marginTop: 5,
flex: 1,
fontSize: 18,
borderWidth: 1,
borderColor: "#555555",
borderRadius: 8,
color: "#555555"
},
button: {
height: 36,
flex: 1,
backgroundColor: "#555555",
borderColor: "#555555",
borderWidth: 1,
borderRadius: 8,
marginTop: 10,
justifyContent: "center"
},
buttonText: {
fontSize: 18,
color: "#ffffff",
alignSelf: "center"
},
});
module.exports = LoginView;
You have to use navigator. please read the documentation as mentioned below. and if you will need then i will share you my code.
Here is an example: NavigatorExample

Categories

Resources