How to make react-native navigation screen fill up ios simulator screen - javascript

I have a problem with react native navigation screen
Here is my problem picture:
enter image description here
As you can see the navigation screen is shown smaller than the simulator screen size.
Here is my related code
Navigation code:
import * as React from 'react';
import {NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
import {createBottomTabNavigator} from '#react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';
import {Text, Dimensions} from 'react-native';
import HomeScreen from '../screens/HomeScreen';
import AboutScreen from '../screens/AboutScreen';
import ProfileScreen from '../screens/ProfileScreen';
const fullScreenWidth = Dimensions.get('window').width;
const Stack = createStackNavigator();
function HomeStackScreen() {
return (
<Stack.Navigator>
<Stack.Screen name="HomeScreen" component={HomeScreen} />
</Stack.Navigator>
);
}
function AboutStackScreen() {
return (
<Stack.Navigator>
<Stack.Screen name="AboutScreen" component={AboutScreen} />
</Stack.Navigator>
);
}
function ProfileStackScreen() {
return (
<Stack.Navigator>
<Stack.Screen name="ProfileScreen" component={ProfileScreen} />
</Stack.Navigator>
);
}
const Tab = createBottomTabNavigator();
function Navigation(props) {
return (
<NavigationContainer>
<Tab.Navigator
screenOptions={({route}) => ({
headerTitle: () => {
return <Text>Header</Text>;
},
tabBarIcon: ({focused, color, size, padding}) => {
let iconName;
if (route.name === 'Home') {
iconName = focused ? 'home' : 'home-outline';
} else if (route.name === 'About') {
iconName = focused
? 'information-circle'
: 'information-circle-outline';
} else if (route.name === 'Profile') {
iconName = focused ? 'person' : 'person-outline';
}
return (
<Ionicons
name={iconName}
size={size}
color={color}
style={{paddingBottom: padding}}
/>
);
},
tabBarActiveTintColor: 'lightseagreen',
tabBarInactiveTintColor: 'grey',
tabBarLableStyle: {fontSize: 16},
tabBarstyle: {width: fullScreenWidth},
})}>
<Tab.Screen name="Home" component={HomeStackScreen} />
<Tab.Screen name="About" component={AboutStackScreen} />
<Tab.Screen name="Profile" component={ProfileStackScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}
export default Navigation;
Screen code(each screen has same format):
import React from 'react';
import {SafeAreaView, Text, StyleSheet} from 'react-native';
const HomeScreen = props => {
return (
<SafeAreaView style={styles}>
<Text>Home Screen</Text>
</SafeAreaView>
);
};
export default HomeScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
App screen:
import 'react-native-gesture-handler';
import * as React from 'react';
import {useState, useEffect} from 'react';
import {Text, View, StyleSheet, Button, Linking} from 'react-native';
import Amplify, {Auth, Hub} from 'aws-amplify';
import awsconfig from './src/aws-exports';
import {Authenticator, withOAuth} from 'aws-amplify-react-native';
import InAppBrowser from 'react-native-inappbrowser-reborn';
import SignUp from './src/components/auth/SignUp';
import ConfirmSignUp from './src/components/auth/ConfirmSignUp';
import SignIn from './src/components/auth/SignIn';
import ForgotPassword from './src/components/auth/ForgotPassword';
import ChangePassword from './src/components/auth/ChangePassword';
import Navigation from './src/components/navigation/Navigation';
import UserContext from './src/components/userContext/UserContext';
async function urlOpener(url, redirectUrl) {
await InAppBrowser.isAvailable();
const {type, url: newUrl} = await InAppBrowser.openAuth(url, redirectUrl, {
showTitle: false,
enableUrlBarHiding: true,
enableDefaultShare: false,
ephemeralWebSession: false,
});
if (type === 'success') {
Linking.openURL(newUrl);
}
}
Amplify.configure({
...awsconfig,
Analytics: {
disabled: true,
},
oauth: {
...awsconfig.oauth,
urlOpener,
},
});
function Home(props) {
return (
<View>
<Navigation {...props} />
<Button title="Sign Out" onPress={() => Auth.signOut()} />
</View>
);
}
const AuthScreens = props => {
console.log(props.authState);
switch (props.authState) {
case 'signIn':
return <SignIn {...props} />;
case 'signUp':
return <SignUp {...props} />;
case 'forgotPassword':
return <ForgotPassword {...props} />;
case 'confirmSignUp':
return <ConfirmSignUp {...props} />;
case 'changePassword':
return <ChangePassword {...props} />;
case 'signedIn':
return <Home />;
case 'verifyContact':
return <Home />;
default:
return <></>;
}
};
const App = props => {
const [user, setUser] = useState({});
useEffect(() => {
Hub.listen('auth', ({payload: {event, data}}) => {
switch (event) {
case 'signIn':
case 'cognitoHostedUI':
getUser().then(userData => setUser(userData));
break;
case 'signOut':
setUser(null);
break;
case 'signIn_failure':
case 'cognitoHostedUI_failure':
console.log('Sign in failure', data);
break;
}
});
getUser().then(userData => setUser(userData));
}, []);
function getUser() {
return Auth.currentAuthenticatedUser()
.then(userData => userData)
.catch(() => console.log('Not signed in'));
}
const {googleSignIn, facebookSignIn} = props;
return (
<View style={styles.container}>
<Authenticator
usernameAttributes="email"
hideDefault={true}
authState="signIn">
<AuthScreens />
</Authenticator>
{!user && (
<View style={{marginBottom: 200}}>
<Text style={{textAlign: 'center'}}> - OR - </Text>
<Button title="Login with Google" onPress={googleSignIn} />
<Button title="Login with Facebook" onPress={facebookSignIn} />
</View>
)}
</View>
);
};
export default withOAuth(App);
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
How to fix this to fill up simulator screen?

I solve this problem by myself.
Actually the problem is in tabBarStyle!!!!
This is fixed code in Navigation.js:
import * as React from 'react';
import {NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
import {createBottomTabNavigator} from '#react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';
import {Text, Dimensions} from 'react-native';
import HomeScreen from '../screens/HomeScreen';
import AboutScreen from '../screens/AboutScreen';
import ProfileScreen from '../screens/ProfileScreen';
const fullScreenWidth = Dimensions.get('window').width;
const Stack = createStackNavigator();
function HomeStackScreen() {
return (
<Stack.Navigator>
<Stack.Screen name="HomeScreen" component={HomeScreen} />
</Stack.Navigator>
);
}
function AboutStackScreen() {
return (
<Stack.Navigator>
<Stack.Screen name="AboutScreen" component={AboutScreen} />
</Stack.Navigator>
);
}
function ProfileStackScreen() {
return (
<Stack.Navigator>
<Stack.Screen name="ProfileScreen" component={ProfileScreen} />
</Stack.Navigator>
);
}
const Tab = createBottomTabNavigator();
function Navigation(props) {
return (
<NavigationContainer>
<Tab.Navigator
screenOptions={({route}) => ({
headerTitle: () => {
return <Text>Header</Text>;
},
tabBarIcon: ({focused, color, size, padding}) => {
let iconName;
if (route.name === 'Home') {
iconName = focused ? 'home' : 'home-outline';
} else if (route.name === 'About') {
iconName = focused
? 'information-circle'
: 'information-circle-outline';
} else if (route.name === 'Profile') {
iconName = focused ? 'person' : 'person-outline';
}
return (
<Ionicons
name={iconName}
size={size}
color={color}
style={{paddingBottom: padding}}
/>
);
},
tabBarActiveTintColor: 'lightseagreen',
tabBarInactiveTintColor: 'grey',
tabBarLableStyle: {fontSize: 16},
tabBarStyle: {width: fullScreenWidth},
})}>
<Tab.Screen name="Home" component={HomeStackScreen} />
<Tab.Screen name="About" component={AboutStackScreen} />
<Tab.Screen name="Profile" component={ProfileStackScreen} />
</Tab.Navigator>
</NavigationContainer>
);
}
export default Navigation;

Related

ERROR The action 'NAVIGATE' with payload {...} was not handled by any navigator in React Native

I have implemented AWS custom UI authenctication in my react native app and React navigation to navigate through the different screens.
While implementing the logical conditions to see if the "User is already logged in or not" I have assigned the screen "Home" for logged in user and screen 'Login' for not logged in user it's working fine and navigating as expected but the console is showing this error when clicking on login button.
ERROR The action 'NAVIGATE' with payload {"name":"Home"} was not handled by any navigator.
Here is the Navigation code:
import React, {useEffect, useState} from 'react'
import {ActivityIndicator, Alert, View} from 'react-native';
import HomeScreen from '../screens/HomeScreen';
import LoginScreen from '../screens/LoginScreen';
import RegisterScreen from '../screens/RegisterScreen';
import ConfirmEmailScreen from '../screens/ConfirmEmailScreen';
import ForgotPassword from '../screens/ForgotPassword';
import NewPasswordScreen from '../screens/NewPasswordScreen';
import { NavigationContainer } from '#react-navigation/native'
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import {Auth, Hub} from 'aws-amplify';
const Stack = createNativeStackNavigator();
const Navigation = () => {
const [user, setUser] = useState(undefined);
//Checking if user is already logged in or not!
const checkUser = async () => {
try {
const authUser = await Auth.currentAuthenticatedUser({bypassCache: true});
setUser(authUser);
} catch(e) {
setUser(null);
}
};
useEffect(() => {
checkUser();
}, []);
useEffect(() => {
const listener = data => {
if (data.payload.event === 'signIn' || data.payload.event === 'signOut') {
checkUser();
}
}
Hub.listen('auth', listener);
return () => Hub.remove('auth', listener);
}, []);
if (user === undefined) {
return (
<View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
<ActivityIndicator/>
</View>
);
}
return (
<NavigationContainer>
<Stack.Navigator>
{/*{If user is logged in navigate him to Homescreen else go throght the Screens based on the user selection */}
{user ? (
<Stack.Screen name='Home' component={HomeScreen}/>
) : (
<>
<Stack.Screen name='Login' component={LoginScreen}/>
<Stack.Screen name='Register' component={RegisterScreen}/>
<Stack.Screen name='ConfirmEmail' component={ConfirmEmailScreen}/>
<Stack.Screen name='ForgotPassword' component={ForgotPassword}/>
<Stack.Screen name='NewPassword' component={NewPasswordScreen}/>
</>
)}
</Stack.Navigator>
</NavigationContainer>
);
};
export default Navigation;
Here is the Login Screen:
import React, {useState} from 'react'
import { View, Text, Image, StyleSheet, useWindowDimensions, TouchableWithoutFeedback, Keyboard, Alert, KeyboardAvoidingView, ScrollView } from 'react-native'
import Logo from '../../../assets/images/logo-main.png'
import CustomButton from '../../components/CustomButton/CustomButton';
import CustomInput from '../../components/CustomInput/CustomInput';
import { useNavigation } from '#react-navigation/native';
import {Auth} from 'aws-amplify';
import {useForm} from 'react-hook-form';
const LoginScreen = () => {
const [loading, setLoading] = useState(false);
const {height} = useWindowDimensions();
const {control, handleSubmit, formState: {errors}} = useForm();
const navigation = useNavigation();
const onLoginPressed = async (data) => {
if(loading) {
return;
}
setLoading(true);
try {
await Auth.signIn(data.username, data.password);
navigation.navigate('Home');
} catch(e) {
Alert.alert('Opps', e.message)
}
setLoading(false);
};
const onForgotPasswordPressed = () => {
navigation.navigate('ForgotPassword');
}
const onRegisterPressed = () => {
navigation.navigate('Register')
}
return (
<KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} style={styles.container}>
<ScrollView contentContainerStyle={{flexGrow:1, justifyContent:'center'}} showsVerticalScrollIndicator={false}>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.root}>
<Image source={Logo} style={[styles.logo, {height : height * 0.2}]} resizeMode={'contain'} />
<CustomInput icon='user' name='username' placeholder='Username' control={control} rules={{required: 'Username is required'}} />
<CustomInput icon='lock' name='password' placeholder='Password' control={control} rules={{required: 'Password is required'}} secureTextEntry={true} />
<CustomButton text={loading ? 'Loading...' : 'Login Account'} onPress={handleSubmit(onLoginPressed)} />
<CustomButton text='Forgot Password?' onPress={onForgotPasswordPressed} type='TERTIARY' />
<CustomButton text="Don't have an account? Create one" onPress={onRegisterPressed} type='TERTIARY' />
</View>
</TouchableWithoutFeedback>
</ScrollView>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
root: {
alignItems: 'center',
padding: 20,
},
logo: {
width: 200,
maxWidth: 300,
maxHeight: 300,
},
});
export default LoginScreen;
Issue
At the time you are calling navigation.navigate('Home') there is no screen called in Home in Navigation because of that ternary that checks whether there is a user or not and renders conditionally your screens. That's why React Naviagation is not happy.
Solution
React Navigation's documention tell us that we shouldn't "manually navigate when conditionally rendering screens​". Means you should find a way to call setUser(user) in Login where setUser is the state setter from Navigation component.
To do so we can use a context and for that change Navigation as follow (I added comments where I changed things):
import React, { createContext, useEffect, useState } from "react";
import { ActivityIndicator, View } from "react-native";
import ConfirmEmailScreen from "../screens/ConfirmEmailScreen";
import ForgotPassword from "../screens/ForgotPassword";
import HomeScreen from "../screens/HomeScreen";
import LoginScreen from "../screens/LoginScreen";
import NewPasswordScreen from "../screens/NewPasswordScreen";
import RegisterScreen from "../screens/RegisterScreen";
import { NavigationContainer } from "#react-navigation/native";
import { createNativeStackNavigator } from "#react-navigation/native-stack";
import { Auth, Hub } from "aws-amplify";
const Stack = createNativeStackNavigator();
// Line I added
export const AuthContext = createContext(null);
const Navigation = () => {
const [user, setUser] = useState(undefined);
//Checking if user is already logged in or not!
const checkUser = async () => {
try {
const authUser = await Auth.currentAuthenticatedUser({ bypassCache: true });
setUser(authUser);
} catch (e) {
setUser(null);
}
};
useEffect(() => {
checkUser();
}, []);
useEffect(() => {
const listener = (data) => {
if (data.payload.event === "signIn" || data.payload.event === "signOut") {
checkUser();
}
};
Hub.listen("auth", listener);
return () => Hub.remove("auth", listener);
}, []);
if (user === undefined) {
return (
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<ActivityIndicator />
</View>
);
}
return (
// Wrapper I added
<AuthContext.Provider value={{ user, setUser }}>
<NavigationContainer>
<Stack.Navigator>
{/*{If user is logged in navigate him to Homescreen else go throght the Screens based on the user selection */}
{user ? (
<Stack.Screen name="Home" component={HomeScreen} />
) : (
<>
<Stack.Screen name="Login" component={LoginScreen} />
<Stack.Screen name="Register" component={RegisterScreen} />
<Stack.Screen name="ConfirmEmail" component={ConfirmEmailScreen} />
<Stack.Screen name="ForgotPassword" component={ForgotPassword} />
<Stack.Screen name="NewPassword" component={NewPasswordScreen} />
</>
)}
</Stack.Navigator>
</NavigationContainer>
</AuthContext.Provider>
);
};
export default Navigation;
Consume AuthContext from Navigation in Login so you are able to call setUser after login, like below (I added comments where I changed thing):
import { useNavigation } from "#react-navigation/native";
import React, { useContext, useState } from "react";
import {
Alert,
Image,
Keyboard,
KeyboardAvoidingView,
ScrollView,
StyleSheet,
TouchableWithoutFeedback,
useWindowDimensions,
View,
} from "react-native";
import Logo from "../../../assets/images/logo-main.png";
import CustomButton from "../../components/CustomButton/CustomButton";
import CustomInput from "../../components/CustomInput/CustomInput";
import { Auth } from "aws-amplify";
import { useForm } from "react-hook-form";
// Line I added
import {AuthContext} from "./Navigation" // ⚠️ use the correct path
const LoginScreen = () => {
// Line I added
const { setUser } = useContext(AuthContext);
const [loading, setLoading] = useState(false);
const { height } = useWindowDimensions();
const {
control,
handleSubmit,
formState: { errors },
} = useForm();
const navigation = useNavigation();
const onLoginPressed = async (data) => {
if (loading) {
return;
}
setLoading(true);
try {
const user = await Auth.signIn(data.username, data.password);
// Line I added
setUser(user);
} catch (e) {
Alert.alert("Opps", e.message);
}
setLoading(false);
};
const onForgotPasswordPressed = () => {
navigation.navigate("ForgotPassword");
};
const onRegisterPressed = () => {
navigation.navigate("Register");
};
return (
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container}
>
<ScrollView
contentContainerStyle={{ flexGrow: 1, justifyContent: "center" }}
showsVerticalScrollIndicator={false}
>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={styles.root}>
<Image
source={Logo}
style={[styles.logo, { height: height * 0.2 }]}
resizeMode={"contain"}
/>
<CustomInput
icon="user"
name="username"
placeholder="Username"
control={control}
rules={{ required: "Username is required" }}
/>
<CustomInput
icon="lock"
name="password"
placeholder="Password"
control={control}
rules={{ required: "Password is required" }}
secureTextEntry={true}
/>
<CustomButton
text={loading ? "Loading..." : "Login Account"}
onPress={handleSubmit(onLoginPressed)}
/>
<CustomButton
text="Forgot Password?"
onPress={onForgotPasswordPressed}
type="TERTIARY"
/>
<CustomButton
text="Don't have an account? Create one"
onPress={onRegisterPressed}
type="TERTIARY"
/>
</View>
</TouchableWithoutFeedback>
</ScrollView>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
root: {
alignItems: "center",
padding: 20,
},
logo: {
width: 200,
maxWidth: 300,
maxHeight: 300,
},
});

How can i add a navigation drawer inside a stack navigator in an already existing project

Hello guys so I wanted to add a navigation DRAWER inside my main screen and I did not know how to nest it with the already existing stack navigator ,
this is my navigation component :
import React from "react";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import ProductsOverviewScreen from "../screens/shop/ProductsOverviewScreen";
import ProductDetails from "../screens/shop/ProductDetailScreen";
import { HeaderButtons,Item } from "react-navigation-header-buttons";
import HeaderButton from '../components/UI/HeaderButton'
import CartScreen from "../screens/shop/CartScreen";
import OrdersScreen from "../screens/shop/OrdersScreen";
const RootNavigation=()=> {
const Stack = createStackNavigator();
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>
);
}
const screenOptions ={
headerShown:true,
headerStyle: {
backgroundColor: 'white',},
headerTintColor: 'aqua',
headerTitleStyle: {
fontWeight: 'bold',
},
};
return(
<NavigationContainer>
<Stack.Navigator initialRouteName='ProductsOverview' screenOptions={screenOptions}>
<Stack.Screen name='ProductsOverview' component={ProductsOverviewScreen} options={({navigation,route})=>({title:'All Products',headerTitleStyle:{fontFamily:'open-sans-bold'},
headerRight:()=>( <HeaderButtons HeaderButtonComponent={HeaderButton}><Item title ='Cart' iconName='md-cart' onPress={()=>{navigation.navigate('CartScreen')}}/></HeaderButtons>)})}/>
<Stack.Screen name='ProductsDetail' component={ProductDetails} options={({route})=>({title:route.params.productTitle,headerTitleStyle:{fontFamily:'open-sans-bold'}})} />
<Stack.Screen name='CartScreen' component={CartScreen} options={{title:'Cart Items', headerTitleStyle:{fontFamily:'open-sans-bold'}}} />
<Stack.Screen name='OrdersScreen' component={OrdersScreen} options={{title:'Orders '}}/>
</Stack.Navigator>
</NavigationContainer>
)
}
export default RootNavigation;
and this is my app.js
import { StatusBar } from 'expo-status-bar';
import { StyleSheet } from 'react-native';
import {createStore , combineReducers} from 'redux';
import { Provider} from 'react-redux';
import AppLoading from 'expo-app-loading';
import * as Font from 'expo-font';
import productsReducer from './store/reducers/products';
import {composeWithDevTools} from 'redux-devtools-extension'
import RootNavigation from './navigation/ShopNavigation';
import cartReducer from './store/reducers/cart'
import { useState } from 'react';
import ordersReducer from './store/reducers/orders'
const rootReducer=combineReducers({
products: productsReducer,
cart: cartReducer,
orders:ordersReducer,
});
const store = createStore(rootReducer,composeWithDevTools());
const fetchFonts=()=>{
return Font.loadAsync({
'open-sans': require('./assets/fonts/OpenSans-Regular.ttf'),
'open-sans-bold': require('./assets/fonts/OpenSans-Bold.ttf')
})
}
export default function App() {
const [fontLoaded,setfontLoaded]= useState(false);
if (!fontLoaded) {
return (
<AppLoading
startAsync={fetchFonts}
onFinish={()=>setfontLoaded(true)}
onError={console.warn}
/>
);
}
return (
<Provider store={store}>
<RootNavigation />
</Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
can you give me an idea how to nest them together I tried using the docs but still full of errors
and Thanks
Drawer Navigator must be a parent to both Stack and Tab navigators. With that knowledge, let we refactor our code as below:
import React from "react";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import ProductsOverviewScreen from "../screens/shop/ProductsOverviewScreen";
import ProductDetails from "../screens/shop/ProductDetailScreen";
import { HeaderButtons, Item } from "react-navigation-header-buttons";
import HeaderButton from "../components/UI/HeaderButton";
import CartScreen from "../screens/shop/CartScreen";
import OrdersScreen from "../screens/shop/OrdersScreen";
import { createDrawerNavigator } from "#react-navigation/drawer";
const RootNavigation = () => {
const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();
const AppStack = () => (
<Stack.Navigator
initialRouteName="ProductsOverview"
screenOptions={screenOptions}
>
<Stack.Screen
name="ProductsOverview"
component={ProductsOverviewScreen}
options={({ navigation, route }) => ({
title: "All Products",
headerTitleStyle: { fontFamily: "open-sans-bold" },
headerRight: () => (
<HeaderButtons HeaderButtonComponent={HeaderButton}>
<Item
title="Cart"
iconName="md-cart"
onPress={() => {
navigation.navigate("CartScreen");
}}
/>
</HeaderButtons>
),
})}
/>
<Stack.Screen
name="ProductsDetail"
component={ProductDetails}
options={({ route }) => ({
title: route.params.productTitle,
headerTitleStyle: { fontFamily: "open-sans-bold" },
})}
/>
<Stack.Screen
name="CartScreen"
component={CartScreen}
options={{
title: "Cart Items",
headerTitleStyle: { fontFamily: "open-sans-bold" },
}}
/>
<Stack.Screen
name="OrdersScreen"
component={OrdersScreen}
options={{ title: "Orders " }}
/>
</Stack.Navigator>
);
return (
<NavigationContainer>
<Drawer.Navigator>
<Drawer.Screen name="MainStack" component={AppStack} />
</Drawer.Navigator>
</NavigationContainer>
);
};
export default RootNavigation;
I omitted component code below as can't access drawer.
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>
);
}
Here a minified version of working implementation
https://snack.expo.dev/#emmbyiringiro/69dc5b

How to successfully logout and navigate back to the main App screen in React-Native?

I need help figuring out the right way to logout and return to the Welcome screen.
Currently, the RootStack queries the redux store for a token, and uses that to determine which group of screens will be available to the user.
If a token exists we go into a TabNavigator called OrgTabs. And that seems to be taking removing the parent navigator. And when I try to logout, the screen I want to navigate to doesn't exist within the navigation object.
Please help! I'd really appreciate
Rootstack.js
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
//screens
import Welcome from '../screens/Welcome';
import SignIn from '../screens/SignIn';
import UserSignIn from '../screens/UserSignIn.js';
import StaffSignIn from '../screens/StaffSignIn';
import StaffSignUp from '../screens/StaffSignUp';
import OrgSignIn from '../screens/OrgSignIn';
import OrgSignUp from '../screens/OrgSignUp';
import OrgHomeScreen from '../screens/org/OrgHomeScreen';
import OrgTabs from '../components/molecules/OrgTabs';
import TestScreen from '../screens/org/TestScreen';
// selecetors and hooks
import { useSelector } from 'react-redux';
import { selectToken, selectRefreshToken } from '../features/user/userSlice';
const Stack = createStackNavigator();
const RootStack = () => {
const token = useSelector(selectToken)
const refreshToken = useSelector(selectRefreshToken)
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: true,
headerTitle:'',
headerTransparent: true
}}
>
{ token ?
(<Stack.Group>
<Stack.Screen name="OrgTabs" component={OrgTabs} />
<Stack.Screen name="Welcome" component={Welcome} />
<Stack.Screen name="TestScreen" component={TestScreen} />
<Stack.Screen name="SignIn" component={SignIn} />
<Stack.Screen name="UserSignIn" component={UserSignIn} />
<Stack.Screen name="StaffSignIn" component={StaffSignIn} />
<Stack.Screen name="StaffSignUp" component={StaffSignUp} />
<Stack.Screen name="OrgSignIn" component={OrgSignIn} />
<Stack.Screen name="OrgSignUp" component={OrgSignUp} />
</Stack.Group>
)
:
// auth screens
(<Stack.Group>
<Stack.Screen name="Welcome" component={Welcome} />
<Stack.Screen name="SignIn" component={SignIn} />
<Stack.Screen name="UserSignIn" component={UserSignIn} />
<Stack.Screen name="StaffSignIn" component={StaffSignIn} />
<Stack.Screen name="StaffSignUp" component={StaffSignUp} />
<Stack.Screen name="OrgSignIn" component={OrgSignIn} />
<Stack.Screen name="OrgSignUp" component={OrgSignUp} />
<Stack.Screen name="OrgTabs" component={OrgTabs} />
</Stack.Group>
)
}
</Stack.Navigator>
</NavigationContainer>
);
}
export default RootStack;
StaffSignIn.js
import React from "react";
import { Text, TextInput, ActivityIndicator } from "react-native";
import { StatusBar } from 'expo-status-bar';
import { Formik, Form } from "formik";
import { useDispatch, useSelector } from "react-redux";
import {
LightContainer, PadlessContainer, FlexHoriztal,
Header1, Header2, Header3, TextLight,
AppLogo, StlyedButton,
Pad_h_medium, Pad_h_small, Pad_w_small} from "../styles/styles";
import { TextLink, MsgBox } from "../components/atoms/Atoms";
import { StyldTextInput } from "../components/molecules/Molecules";
import { StyledFormArea } from "../components/organisms/Organisms";
import KeyboardAvoidingWrapper from "../components/organisms/KeyboardAvoidingWrapper";
import * as SecureStore from "expo-secure-store";
import axios from "axios";
import { setToken } from "../features/user/userSlice";
import {getToken} from "../features/user/User";
const logo_img = require("../assets/logo_red.png");
const chalk = require('chalk');
const StaffSignIn = ({navigation}) => {
[message, setMessage] = React.useState("");
[messageStatus, setMessageStatus] = React.useState("failed");
[hidePassword, setHidePassword] = React.useState(true);
const dispatch = useDispatch();
const handleSubmit = (values, setSubmitting) => {
const url = "https://dandle.dustinc.dev/signin/staff";
axios.post(url, values)
.then( (response) => {
const result = response.data;
const {success, user, token, refreshToken} = response.data;
if(success === true) {
setMessageStatus("success");
setMessage("sign in successful");
storeToken(token, refreshToken);
dispatch(setToken(token));
navigation.navigate("OrgTabs");
}
else if (success === false) {
setMessageStatus("failed");
setMessage("sign in failed");
}
setSubmitting(false);
})
.catch(err => {
setSubmitting(false);
// setMessage("Oops! Network error. Try again soon");
if (err.response.status === 401) {
setMessage("Invalid username or password");
}
else {
setMessage("Oops! Network error. Try again soon");
}
})
.finally(() => {
setSubmitting(false);
});
}
// function that will store a token and refresh token in react-native-keychain
async function storeToken (token, refreshToken) {
SecureStore.setItemAsync("token", token)
.then(() => {
SecureStore.setItemAsync("refreshToken", refreshToken)
.then(() => {
dispatch(setToken(token));
dispatch(setToken(refreshToken));
console.log("\x1b[32m successfully stored token and refresh-token\n");
console.log("\x1b[0m token: ", token,'\n');
console.log("refreshToken: ", refreshToken, '\n');
})
.catch(err => {
console.log(err);
});
})
.catch(err => {
console.log(err);
});
}
return (
<KeyboardAvoidingWrapper>
<LightContainer>
<StatusBar style="dark" />
<PadlessContainer>
<Pad_h_medium /><Pad_h_medium />
<Formik
initialValues={{
username: "",
password: "",
}}
onSubmit={(values, {setSubmitting}) => {
handleSubmit(values, setSubmitting);
}}
>
{
({handleChange, handleBlur, handleSubmit, isSubmitting, values}) => (
<StyledFormArea justify='center'>
<StyldTextInput
label="Username"
placeholder="johndoe"
onChangeText={handleChange("username")}
value={values.username}
/>
<StyldTextInput
label="Password"
placeholder="* * * * * * *"
secureTextEntry={hidePassword}
value={values.password}
onChangeText={handleChange('password')}
isPassword={true}
hidePassword={hidePassword}
setHidePassword={setHidePassword}
/>
<Pad_h_medium /><Pad_h_medium /><Pad_h_medium />
<Pad_h_medium /><Pad_h_medium /><Pad_h_medium />
<MsgBox type={messageStatus}>{message}</MsgBox>
{!isSubmitting && <StlyedButton onPress={handleSubmit} width='100%'>
<TextLight>Sign in</TextLight>
</StlyedButton>}<Pad_h_small />
{isSubmitting && <StlyedButton width='100%' disabled={true}>
<ActivityIndicator size="small" color="#fff" />
</StlyedButton>}<Pad_h_small />
<FlexHoriztal justify='center'>
<Header2>Don't have an account?</Header2>
<TextLink onPress={()=> navigation.navigate('StaffSignUp')}>
<Header2>Register</Header2>
</TextLink>
</FlexHoriztal>
</StyledFormArea>
)
}
</Formik>
</PadlessContainer>
</LightContainer>
</KeyboardAvoidingWrapper>
);
}
export default StaffSignIn;
OrgTabs.js
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import {Octicons} from '#expo/vector-icons';
//screens
import OrgSettings from '../../screens/org/OrgSettings';
import OrgHomeScreen from '../../screens/org/OrgHomeScreen';
import OrgAnalytics from '../../screens/org/OrgAnalytics';
import OrgChat from '../../screens/org/OrgChat';
const Tab = createBottomTabNavigator();
export default function OrgTabs() {
return (
<NavigationContainer
independent={true}
>
<Tab.Navigator
screenOptions={{
tabBarShowLabel: false,
tabBarStyle: {
position: 'absolute',
backgroundColor: '#f38484',
borderTopRightRadius: 2,
borderTopLeftRadius: 2,
},
headerTransparent : true,
headerShown: false,
tabBarActiveBackgroundColor: '#d64547',
}}
>
<Tab.Screen
name="Settings"
component={OrgSettings}
options={{
tabBarIcon: () => {
return(
<Octicons name='gear' size={25} color='white'/>
)
}
}}
/>
<Tab.Screen
name="Home"
component={OrgHomeScreen}
options={{
tabBarIcon: () => {
return(
<Octicons name='home' size={25} color='white'/>
)
}
}}
/>
<Tab.Screen
name="Chat"
component={OrgChat}
options={{
tabBarIcon: ({size,focused,color}) => {
return(
<Octicons name='comment-discussion' size={25} color='white'/>
)
}
}}
/>
<Tab.Screen
name="Analytics"
component={OrgAnalytics}
options={{
tabBarIcon: ({size,focused,color}) => {
return(
<Octicons name='graph' size={25} color='white'/>
)
}
}}
/>
</Tab.Navigator>
</NavigationContainer>
);
}
So the solution I came up with, was to display the message "Logged out" and then set the token in redux to Null.
And finally, reload the app using the Updates package, which is part of Expo.
So when you logout, the app is reloaded and the check for a token is repeated.
Try this,I Hope it will work.
const logout=()=>{
console.log("logout");
AsyncStorage.getAllKeys()
.then(keys => AsyncStorage.multiRemove(keys)).then(() => navigation.reset({ index: 0, routes: [{ name: "Login" }], }));
}

Weird behaviour in React Navigation V6

I am facing some weird behaviour with react navigation version 6.
When I have a headerLeft property assigned my headerTitleStyle doesn't work anymore.
So if I assign some value to headerLeft to place an icon let's say, my headerTitleStyle is not applying styles to the title, which is really weird.
home.navigator.js
import React from "react";
import { createNativeStackNavigator } from "#react-navigation/native-stack";
import { ProductsScreen } from "../screens/products.screen";
import { colors } from "../theme/colors";
import { fonts } from "../theme/fonts";
import { MenuIcon } from "../components/menu-icon.component";
import { TouchableOpacity } from "react-native";
const Stack = createNativeStackNavigator();
export const HomeNavigator = () => {
return (
<Stack.Navigator
initialRouteName="Products"
screenOptions={{
headerTitleStyle: { <<//Doesn't work when headerLeft is assigned.
fontFamily: fonts.black,
},
headerStyle: {
backgroundColor: colors.bg.secondary,
color:colors.brand.secondary,
},
headerLeft: () => (
<TouchableOpacity>
<MenuIcon height={52} width={52} weight={1.5} color={colors.brand.secondary} />
</TouchableOpacity>
),
}}
>
<Stack.Screen
options={{ title: "Marketplace", headerShadowVisible: false }}
name="Products"
component={ProductsScreen}
/>
</Stack.Navigator>
);
};
app.navigator.js:
import React from "react";
import { createMaterialBottomTabNavigator } from "#react-navigation/material-bottom-tabs";
import { Ionicons } from "#expo/vector-icons";
import { colors } from "../theme/colors";
import { fonts } from "../theme/fonts";
import { Text } from "react-native";
import { HomeNavigator } from "./home.navigator";
import { CartScreen } from "../screens/cart.screen";
import { SearchScreen } from "../screens/search.screen";
const Tab = createMaterialBottomTabNavigator();
export const AppNavigator = () => (
<Tab.Navigator
initialRouteName="Products"
shifting={true}
screenOptions={({ route }) => ({
tabBarLabel: (
<Text style={{ fontFamily: fonts.bold, textAlign: "center" }}>
{route.name}
</Text>
),
tabBarIcon: ({ focused, color }) => {
let iconName;
if (route.name === "Products") {
iconName = focused ? "home-sharp" : "home-outline";
} else if (route.name === "Search") {
iconName = focused ? "search" : "search-outline";
} else {
iconName = focused ? "cart" : "cart-outline";
}
// You can return any component that you like here!
return <Ionicons name={iconName} size={20} color={color} />;
},
})}
barStyle={{
backgroundColor: colors.bg.secondary,
fontFamily: fonts.regular,
}}
activeColor={colors.brand.secondary}
inactiveColor="gray"
>
<Tab.Screen name="Products" component={HomeNavigator} />
<Tab.Screen name="Search" component={SearchScreen} />
<Tab.Screen name="Cart" component={CartScreen} />
</Tab.Navigator>
);
Thanks in advance!

How to go to another screen in top tab navigation in react native

I want to go out of top tab navigation but it unable to navigate. It's giving error The action 'NAVIGATE' with payload {"name":"LoginPage"} was not handled by any navigator.
Do you have a screen named 'LoginPage'?
If you're trying to navigate to a screen in a nested navigator, see https://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nested-navigator
I use nesting navigation also but not work. My Screens are below
Top tab navigation screen
import * as React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createMaterialTopTabNavigator } from '#react-navigation/material-top-tabs';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import ProfileData from './profiledata';
import ProfileLikeData from './profilelikedata';
import Fontisto from 'react-native-vector-icons/Fontisto';
const Tab = createMaterialTopTabNavigator();
export default function App() {
return (
<NavigationContainer>
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color }) => {
let iconName;
let size;
if (route.name === 'Data') {
iconName = focused
? 'nav-icon-grid'
: 'nav-icon-grid';
size = focused
? 25
: 25;
} else if (route.name === 'Like') {
iconName = focused ? 'heart' : 'heart';
size = focused
? 20
: 20;
}
return <Fontisto name={iconName} size={size} color={color} />;
},
})}
tabBarOptions={{
activeTintColor: '#d40786',
inactiveTintColor: 'white',
showIcon:true,
showLabel:false,
indicatorStyle: {
width: 0, height: 0, elevation: 0,
},
tabStyle: { width: wp('52%'),borderRightWidth:1,borderColor:'white' },
style: { backgroundColor:'trasparent',borderTopWidth:0.5,borderColor:'white',paddingBottom:5 },
}}
>
<Tab.Screen name="Data" component={ProfileData} />
<Tab.Screen name="Like" component={ProfileLikeData} />
</Tab.Navigator>
</NavigationContainer>
);
}
profiledata.js
import React from 'react';
import { View, StyleSheet, Text,ImageBackground,TouchableOpacity,Image } from 'react-native';
import { FlatGrid } from 'react-native-super-grid';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import { RFPercentage, RFValue } from "react-native-responsive-fontsize";
import Toast from 'react-native-simple-toast';
export default class ProfileData extends React.Component {
constructor(props) {
super(props);
this.state = {
videos:[],
loginid:'',
paused:true,
};
}
static navigationOptions = {
headerShown: false,
};
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<FlatGrid
data={this.state.videos}
spacing={0}
renderItem={({ item }) => (
<TouchableOpacity onPress={()=>navigate('LoginPage')} style={{flex:1}}>
// some data
</TouchableOpacity>
)}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
// paddingHorizontal:wp('2%'),
backgroundColor:'black',
height: hp('100%'),
},
});
You should create another stack that has your login screen or add the login screen in the tab navigator.
for the first do something like this in your app.js
import { createStackNavigator } from '#react-navigation/stack';
import LoginScreen from './LoginScreen'; //Just import the login screen
const AuthStack = createStackNavigator();
const AuthStackScreen = () => (
<AuthStack.Navigator>
<AuthStack.Screen
name="LoginPage"
component={LoginScreen}
/>
</AuthStack.Navigator>
);
//Then in your profiledata.js;
<TouchableOpacity onPress={()=>navigate('LoginPage')} style={{flex:1}}>
// some data
</TouchableOpacity>
And for the second option just add the login screen in your tab navigator;
<Tab.Screen name="Data" component={ProfileData} />
<Tab.Screen name="Like" component={ProfileLikeData} />
<Tab.Screen name="LoginPage" component={LoginScreen} /> //Don't forget to import it

Categories