How can ı create login authentication from a tab screen using react navigation? - javascript

I designed two tab screens. One of them can be accessed by everyone ,we need to login to the other. I am using API to login. If the username and password are correct, the login process is completed. But after logging in , ı cannot switch to the main page screen without refreshing from console. Likewise, when I want to logout , I need to refresh from console. I could not do the opening process directly, I think there is a problem with my stack connections. Stack connection is App.js --> MainTabScreen.js --> SettingScreen.js --> ListScreen.js
1.png - App.js --> MainTabScreen.js
2.png - SettingScreen.js --> ListScreen.js
`
[SplashScreen][1]MainScreen
//App.js
import 'react-native-gesture-handler';
import React , {useEffect} from 'react';
import { StyleSheet } from 'react-native';
//Navigation
import { NavigationContainer } from '#react-navigation/native';
//Mobx
import { observer } from 'mobx-react';
//Store
import { store } from './STORE/index'
//Async
import AsyncStorage from '#react-native-async-storage/async-storage';
//Screens
import MainTabScreen from './SCREENS/TABS/MainTabScreen';
export default observer(() => {
useEffect(() => {
(async () => {
const token = await AsyncStorage.getItem('id_token');
store.setStore('SET_TOKEN', token);
})();
}, []);
return (
<NavigationContainer>
<MainTabScreen/>
</NavigationContainer>
)
})
const styles = StyleSheet.create({});
import React , { useEffect , Component} from 'react';
import { StyleSheet, Image, Text, View ,Dimensions, TextInput} from 'react-native';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { createStackNavigator} from '#react-navigation/stack';
//Store
import { store } from '../../STORE/index';
//Async
import AsyncStorage from '#react-native-async-storage/async-storage';
//Screens
import HomeScreen from './HomeScreen';
import SettingScreen from './SettingScreen';
import TestScreen from './TestScreen';
//menuScreens
import WhiteListScreen from '../MENUSCREEN/WhiteListScreen';
import Reports from '../MENUSCREEN/Reports';
import SendNotifications from '../MENUSCREEN/SendNotifications';
//Color
import COLORS from '../../COLOR/color'
//Vectoricons
import { Ionicons } from '#expo/vector-icons';
import { BlurView } from 'expo-blur';
//MainTabScreen.js
const WINDOW_WIDTH = Dimensions.get('window').width;
const WINDOW_HEIGHT = Dimensions.get('window').height;
const HomeStack = createStackNavigator();
const SettingsStack = createStackNavigator();
const TestStack = createStackNavigator();
const Tab = createBottomTabNavigator();
function MainTabScreen({navigation}) {
useEffect(() => {
(async () => {
const token = await AsyncStorage.getItem('id_token');
const ip_address = await AsyncStorage.getItem('ip_address');
store.setStore('SET_TOKEN', token);
store.setStore('SET_IPADDRESS', ip_address);
})();
}, []);
return (
<Tab.Navigator screenOptions={{
tabBarStyle: { position: 'absolute' ,backgroundColor: 'black'},
tabBarBackground: () => (
<BlurView tint="light" intensity={20} style={StyleSheet.absoluteFill} />
),
}} >
<Tab.Screen
name="Home"
component={HomeStackScreen}
options={{
tabBarLabel:'Home',
tabBarLabelStyle: {
fontSize: 12,
},
headerShown: false,
tabBarIcon: ({color, size}) => (
<Ionicons name="home-outline" color={color} size={20}
/>),
tabBarActiveTintColor: COLORS.rawColor,
tabBarInactiveTintColor: 'gray',
}}
>
</Tab.Screen>
<Tab.Screen
name="Setting"
component={SettingStackScreen}
options={{
tabBarLabel:'Settings',
tabBarLabelStyle: {
fontSize: 12,
},
headerShown: false,
tabBarIcon: ({color, size}) => (
<Ionicons name="settings-outline" color={color} size={20}
/>),
tabBarActiveTintColor: COLORS.rawColor,
tabBarInactiveTintColor: 'gray',
}}
/>
<Tab.Screen
name="Test"
component={TestStackScreen}
options={{
tabBarLabel:'Test',
tabBarLabelStyle: {
fontSize: 12,
},
headerShown: false,
tabBarIcon: ({color, size}) => (
<Ionicons name="close" color={color} size={20}
/>),
tabBarActiveTintColor: COLORS.rawColor,
tabBarInactiveTintColor: 'gray',
}}
/>
</Tab.Navigator>
);
};
export default MainTabScreen;
const TestStackScreen = ({ navigation }) => (
<TestStack.Navigator screenOptions={{
headerTransparent: { position: 'absolute' ,backgroundColor: 'black'},
tabBarBackground: () => (
<BlurView tint="light" intensity={30} style={StyleSheet.absoluteFill} />
),
headerTintColor: '#000',
}}>
<TestStack.Screen name="menu" component={TestScreen}
options={{
headerTitle: (props) => ( // App Logo
<Image
style={{ width: Platform.OS === 'ios' ? 120 : 100,
height: Platform.OS === 'ios' ? 100 : 50,
}}
source={require('../../assets/Optima-logo.png')}
resizeMode='contain'
/>),
headerRight: () => (
<Ionicons style={styles.drawerStyle}
name="settings"
color="black"
size={25}
backgroundColor="#E2E7EA"
onPress={() => navigation.openDrawer()}> </Ionicons>
)
}} />
<TestStack.Screen name="WhiteListScreen" component={WhiteListScreen}
options={{
headerTitle: (props) => ( // App Logo
<Image
style={{ width: Platform.OS === 'ios' ? 120 : 100,
height: Platform.OS === 'ios' ? 100 : 50,
}}
source={require('../../assets/Optima-logo.png')}
resizeMode='contain'
/>),
headerRight: () => (
<Ionicons style={styles.drawerStyle}
name="settings"
color="black"
size={25}
backgroundColor="#E2E7EA"
onPress={() => navigation.openDrawer()}> </Ionicons>
)
}} />
<TestStack.Screen name="Reports" component={Reports}
options={{
headerTitle: (props) => ( // App Logo
<Image
style={{ width: Platform.OS === 'ios' ? 120 : 100,
height: Platform.OS === 'ios' ? 100 : 50,
}}
source={require('../../assets/Optima-logo.png')}
resizeMode='contain'
/>),
headerRight: () => (
<Ionicons style={styles.drawerStyle}
name="settings"
color="black"
size={25}
backgroundColor="#E2E7EA"
onPress={() => navigation.openDrawer()}> </Ionicons>
)
}} />
<TestStack.Screen name="SendNotifications" component={SendNotifications}
options={{
headerTitle: (props) => ( // App Logo
<Image
style={{ width: Platform.OS === 'ios' ? 120 : 100,
height: Platform.OS === 'ios' ? 100 : 50,
}}
source={require('../../assets/Optima-logo.png')}
resizeMode='contain'
/>),
headerRight: () => (
<Ionicons style={styles.drawerStyle}
name="settings"
color="black"
size={25}
backgroundColor="#E2E7EA"
onPress={() => navigation.openDrawer()}> </Ionicons>
)
}} />
</TestStack.Navigator>
);
const HomeStackScreen = ({ navigation }) => (
<HomeStack.Navigator screenOptions={{
headerTransparent: { position: 'absolute' ,backgroundColor: 'black'},
tabBarBackground: () => (
<BlurView tint="light" intensity={30} style={StyleSheet.absoluteFill} />
),
headerTintColor: '#000',
}}>
<HomeStack.Screen name="menu" component={HomeScreen}
options={{
headerTitle: (props) => ( // App Logo
<Image
style={{ width: Platform.OS === 'ios' ? 120 : 100,
height: Platform.OS === 'ios' ? 100 : 50,
}}
source={require('../../assets/Optima-logo.png')}
resizeMode='contain'
/>),
headerRight: () => (
<Ionicons style={styles.drawerStyle}
name="settings"
color="black"
size={25}
backgroundColor="#E2E7EA"
onPress={() => navigation.openDrawer()}> </Ionicons>
)
}} />
</HomeStack.Navigator>
);
const SettingStackScreen = ({ navigation }) => (
<SettingsStack.Navigator screenOptions={{
headerTransparent: { position: 'absolute' ,backgroundColor: 'black'},
tabBarBackground: () => (
<BlurView tint="light" intensity={30} style={StyleSheet.absoluteFill}/>
),
headerTintColor: '#000',
}}>
<SettingsStack.Screen name="SettingScreen" component={SettingScreen}
options={{
headerTitle: (props) => ( // App Logo
<Image
style={{ width: Platform.OS === 'ios' ? 120 : 120, height: Platform.OS === 'ios' ? 120 : 120 }}
source={require('../../assets/Optima-logo.png')}
resizeMode='contain'
/>),
headerRight: () => (
<Ionicons style={styles.drawerStyle}
name="settings"
color="black"
size={25}
backgroundColor="#E2E7EA"
onPress={() => navigation.openDrawer()}> </Ionicons>
)
}} />
{/* {store.token ?
<Stack.Screen
options={{headerShown: false}}
name="SignInScreen" component={SignInScreen}/>
:
<Stack.Screen
name="ListScreen" component={ListScreen}/>
} */}
{/* <Stack.Screen
options={{headerShown: false}}
name="SignInScreen" component={SignInScreen}/>
<Stack.Screen
name="ListScreen" component={ListScreen}/>
<Stack.Screen
name="WhiteListScreen" component={WhiteListScreen}/>
*/}
</SettingsStack.Navigator>
);
});
//SettingScreen.js
import React, { useEffect } from "react";
import {
Dimensions,
StyleSheet,
ImageBackground,
View
} from "react-native";
import { ActivityIndicator } from "react-native-paper";
import { createStackNavigator } from "#react-navigation/stack";
//Store
import { store } from "../../STORE/index";
//Color
import COLORS from "../../COLOR/color";
//Screens
import SignInScreen from "../SignInScreen";
import ListScreen from "../TABS/ListScreen";
import CashierSignIn from "../TABS/CashierSignIn";
const WINDOW_WIDTH = Dimensions.get("window").width;
const WINDOW_HEIGHT = Dimensions.get("window").height;
const Stack = createStackNavigator();
const ListStack = createStackNavigator();
const userToken = store.token;
export default function SettingSreen({ navigation }) {
const [isLoading, setIsLoading] = React.useState(true);
useEffect(() => {
setTimeout(() => {
setIsLoading(false);
}, 1000)
}, []);
if (isLoading && !userToken) {
return (
<View>
<ActivityIndicator size="large" />
</View>
)
}
return (
<ImageBackground
source={require("../../IMAGE/background3.png")}
style={{ width: WINDOW_WIDTH, height: WINDOW_HEIGHT }}
>
{!userToken ? (
<Stack.Navigator ListScreen={props => <ListScreen {...props} />}
screenOptions={{ headerShown: false }} >
<Stack.Screen
name="CashierSignIn"
component={CashierSignIn}
/>
<Stack.Screen
name="SignInScreen"
component={SignInScreen}
/>
</Stack.Navigator>
) : (
<ListStack.Navigator screenOptions={{ headerShown: false }}>
<ListStack.Screen
name="ListScreen"
component={ListScreen}
/>
</ListStack.Navigator>
)}
</ImageBackground>
);
}
const styles = StyleSheet.create({});
import React, { Component } from "react";
import {
Text,
View,
Dimensions,
StyleSheet,
ImageBackground,
TouchableOpacity,
} from "react-native";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
//Translation
import i18n from "../../TRANSLATION/I18n";
//Store
import { store } from "../../STORE/index";
//SignIn Screen
import SignInScreen from "../SignInScreen";
//Color
import COLORS from "../../COLOR/color";
//Screens
import ListScreen from "./ListScreen";
//CashierSignIn.js
const WINDOW_WIDTH = Dimensions.get("window").width;
const WINDOW_HEIGHT = Dimensions.get("window").height;
const Stack = createStackNavigator();
export default function CashierSignIn({ navigation }) {
return (
<ImageBackground
source={require("../../IMAGE/background3.png")}
style={{ width: WINDOW_WIDTH, height: WINDOW_HEIGHT }}
>
<View style={styles.container}>
<Text style={styles.logo}></Text>
<TouchableOpacity>
<Text style={styles.forgot}></Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => navigation.navigate("SignInScreen")}
style={styles.loginBtn}
>
<Text style={styles.loginText}> Cashier Sign In </Text>
</TouchableOpacity>
</View>
</ImageBackground>
);
}
//SignInScreen and List Screen
import React, { useState, useEffect } from "react";
import {
View,
Text,
Dimensions,
StyleSheet,
TouchableOpacity,
ImageBackground,
TextInput,
LogBox,
Alert
} from "react-native";
//Axios
import axios from 'axios';
import { ActivityIndicator } from "react-native-paper";
//Store
import { store } from "../STORE/index";
//COLOR
import COLORS from "../COLOR/color";
//Icons
import Icon from "react-native-vector-icons/Ionicons";
//AsyncStorage
import AsyncStorage from '#react-native-async-storage/async-storage';
LogBox.ignoreLogs([
'Require cycle:'
]);
const WINDOW_WIDTH = Dimensions.get("window").width;
const WINDOW_HEIGHT = Dimensions.get("window").height;
export default function SignInScreen({ navigation }) {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [isLoading, setIsLoading] = React.useState(true);
useEffect(() => {
setTimeout(() => {
setIsLoading(false);
}, 1000)
}, []);
if (isLoading) {
return (
<View>
<ActivityIndicator size="large" />
</View>
)
}
const loginUser = () => {
if (!username.trim() || !password.trim()) {
Alert.alert(
'' + i18n.t('usernamePasswordValid'),
''
[
{ text: i18n.t('ok'), onPress: () => null }
]
);
return;
} else {
axios.get(`http://172.16.55.36:8004/api/values/gettoken?username=${username}&password=${password}`)
.then((response) => {
console.log(response)
AsyncStorage.setItem('id_token', response.data.data).then(() => {
store.setStore('SET_TOKEN', response.data.data)
setIsLoading(true);
})
})
.catch((error) => {
console.log(error);
})
}
}
return (
<ImageBackground
source={require("../IMAGE/background3.png")}
style={{ width: WINDOW_WIDTH, height: WINDOW_HEIGHT }}
>
<View style={styles.header}>
<TouchableOpacity onPress={() => navigation.navigate('CashierSignIn')}>
<Text alignItems="center">
<Icon name="close" color={COLORS.rawColor} size={30} />
</Text>
</TouchableOpacity>
</View>
<View style={styles.container}>
<Text style={styles.logo}>Optima Ticketing App</Text>
<View style={styles.inputView}>
<TextInput
style={styles.inputText}
placeholder="Username"
placeholderTextColor={COLORS.white}
onChangeText={(username) => setUsername(username)}
/>
</View>
<View style={styles.inputView}>
<TextInput
secureTextEntry
style={styles.inputText}
placeholder="Password"
placeholderTextColor={COLORS.white}
onChangeText={(password) => setPassword(password)}
/>
</View>
<TouchableOpacity onPress={() => navigation.navigate('SignUpScreen')}>
<Text style={styles.forgot}>Forgot Password?</Text>
</TouchableOpacity>
{/* <TouchableOpacity onPress={loginUser ? navigation.navigate('ListScreen') : alert("test")} style={styles.loginBtn}> */}
<TouchableOpacity onPress={loginUser} style={styles.loginBtn}>
<Text style={styles.loginText}>LOGIN</Text>
</TouchableOpacity>
<TouchableOpacity>
<Text onPress={() => navigation.navigate('SignUpScreen')}
style={styles.loginText} >Signup</Text>
</TouchableOpacity>
</View>
</ImageBackground>
);
}
import React, { useState } from "react";
import {
View,
Text,
Dimensions,
StyleSheet,
TouchableOpacity,
ImageBackground,
} from 'react-native';
//Store
import { store } from "../../STORE/index";
//AsyncStorage
import AsyncStorage from '#react-native-async-storage/async-storage';
const WINDOW_WIDTH = Dimensions.get('window').width;
const WINDOW_HEIGHT = Dimensions.get('window').height;
function ListScreen({ navigation }) {
return (
<ImageBackground
source={require("../../IMAGE/background3.png")}
style={{ width: WINDOW_WIDTH, height: WINDOW_HEIGHT }}
>
<View style={styles.container}>
<TouchableOpacity onPress={() => navigation.navigate('WhiteListScreen')}>
<Text>White List</Text>
</TouchableOpacity>
<TouchableOpacity >
<Text>2.screen</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={async () => {
await AsyncStorage.removeItem('id_token')
.then(() => store.setStore('SET_TOKEN', null))
.then(() => navigation.goBack())
}}>
<Text style={styles.loginText}> Log Out </Text>
</TouchableOpacity>
</View>
</ImageBackground>
)
}
export default ListScreen;

I would create a context or utility that checks for login status. Then make the drawer conditionally render a login screen/button, or whatever content you'd like, based on that status.

Related

How can I implement swipe up navigation with Stacks in react-native similar to TikTok?

In App.tsx, I have:
export default function App() {
const Stack = createNativeStackNavigator();
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='feed' screenOptions={{ headerShown: false, gestureDirection: 'vertical' }}>
<Stack.Screen name="feed" component={IvoryFeedScreen} />
<Stack.Screen name="home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
How can I have these stacks swipe-up-able like in TikTok?
you can use react-native-pager-view to implement scroll same like tiktok
import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
import PagerView from 'react-native-pager-view';
const MyPager = () => {
return (
<PagerView style={styles.pagerView} initialPage={0}>
<View key="1" style={styles.page}>
<Text>First page</Text>
</View>
<View key="2" style={styles.page}>
<Text>Second page</Text>
</View>
</PagerView>
);
};
const styles = StyleSheet.create({
pagerView: {
flex: 1,
},
page: {
flex: 1,
},
});
you can use ScrollView for swiper
try This Example
const abc = [1, 2, 4];
<FlatList
horizontal={true}
data={abc}
maxToRenderPerBatch={1}
bounces={false}
windowSize={1}
pagingEnabled={true}
snapToAlignment={'end'}
snapToInterval={SCREEN_WIDTH}
decelerationRate={'fast'}
showsHorizontalScrollIndicator={false}
renderItem={({item, index}) => {
return (
<View
style={{
width: SCREEN_WIDTH,
backgroundColor: index === 1 ? 'red' : 'yellow',
}}></View>
);
}}
/>
use snapToInterval in Flatlist
like
import VideoPlayer from 'react-native-video-player'
import { Dimensions } from "react-native";
const {width, height} = Dimensions.get("window");
<FlatList
data={videosList}
snapToInterval={height/2}
decelerationRate="fast"
showsVerticalScrollIndicator={false}
renderItem={({item}) => (
<VideoPlayer
video={{ uri: item.source }}
videoWidth={witdh}
videoHeight={height}
thumbnail={{ uri: item.thumbnail }}
/>
)}
keyExtractor={(item) => item.id}/>
where
const videosList=[
{id: '1', source: 'some URL', thumbnail:'some url'},
{id: '2', source: 'some URL', thumbnail:'some url'},
]

How to open a modal in drawer headerRight icon button?

I am new to react native and working on a dummy project. I use the react-navigation to set the header and headerRight and place a icon in the right side of the header. Now i want to open a modal whenever user click the icon it will show a modal. I tried many things but didn't find any proper solution. Now i am stuck and post this question. I am placing my code below.
Here is my Code:
//Navigation of my app
import * as React from "react";
import { View, TouchableOpacity, StyleSheet } from "react-native";
import { AntDesign, Fontisto } from "#expo/vector-icons";
import { createDrawerNavigator } from "#react-navigation/drawer";
import { createStackNavigator } from "#react-navigation/stack";
import AccountsScreen from "../screens/AccountsScreen";
import FavouritesScreen from "../screens/FavouritesScreen";
import HomeScreen from "../screens/HomeScreen";
import SettingsScreen from "../screens/SettingsScreen";
import TrendsScreen from "../screens/TrendsScreen";
import { createMaterialTopTabNavigator } from "#react-navigation/material-top-tabs";
import { Dimensions } from "react-native";
import Income from "../screens/Income";
import Expense from "../screens/Expense";
import FundTransferModal from "../components/Accounts/FundTransferModal";
const AppStack = () => {
return(
<Stack.Navigator mode="modal" headerMode="none">
<Stack.Screen name="Modal" component={FundTransferModal} />
</Stack.Navigator>
)
}
const AppDrawer = () => {
return (
<Drawer.Navigator
initialRouteName="Home"
screenOptions={{
headerShown: true,
}}
>
<Drawer.Screen
name="Home"
component={HomeScreen}
options={{
headerRight: () => {
return (
<TouchableOpacity onPress={() => AppStack() }>
<View style={styles.icons}>
<AntDesign name="piechart" size={30} color="#29416F" />
</View>
</TouchableOpacity>
);
},
}}
/>
<Drawer.Screen name="Accounts" component={AccountsScreen} options={{
headerRight: () => {
return (
<TouchableOpacity>
<View style={styles.icons}>
<Fontisto name="arrow-swap" size={24} color="#29416F" onPress={() =>{return <FundTransferModal />}} />
</View>
</TouchableOpacity>
);
},
}} />
<Drawer.Screen name="Categories" component={CategoriesTabScreens} />
<Drawer.Screen name="Trends" component={TrendsScreen} />
<Drawer.Screen name="Favourites" component={FavouritesScreen} />
<Drawer.Screen name="Settings" component={SettingsScreen} />
</Drawer.Navigator>
);
};
export default AppDrawer;
const styles = StyleSheet.create({
icons:{
marginRight:20,
}
})
//The Modal which i want to open
import React, { Fragment, useState } from "react";
import { globalStyles } from "../../style/Global";
import { AntDesign, Entypo } from "#expo/vector-icons";
import { MaterialCommunityIcons } from "#expo/vector-icons";
import { Formik } from "formik";
import * as yup from "yup";
import { Picker } from "#react-native-picker/picker";
import SubmitButton from "../SubmitButton";
import { ExampleUncontrolledVertical } from "../../assets/ExampleUncontrolledVertical";
import {
Modal,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
Button,
Keyboard,
ScrollView,
} from "react-native";
import DatePiker from "../DatePikers";
export default function FundTransferModal({navigation}) {
const [fundModal, setFundModal] = useState(true);
const [selectedValue, setValue] = useState(0);
showFundModal = () => {
setFundModal(true);
};
closeFundModal = () => {
setFundModal(false);
};
const validations = yup.object({
text: yup.string().required().min(3),
});
const values = ["Cash", "Bank", "Other"];
const valuesTwo = ["Cash", "Bank", "Other"]
const initialValues = { value: "", valueTwo: "" };
return (
<Modal visible={fundModal} animationType="fade">
<View style={globalStyles.modalHeader}>
<AntDesign
name="arrowleft"
size={30}
onPress={() => closeFundModal()}
/>
<Text style={styles.headerText}>Transfer</Text>
</View>
<Formik
validationSchema={validations}
initialValues={{ amount: "" , notes:"" }}
onSubmit={(values, actions) => {
actions.resetForm();
console.log(values);
}}
>
{(props) => (
<Fragment>
<ScrollView>
<View style={styles.container}>
<View style={styles.box}>
<View style={styles.picker}>
<Picker
mode="dropdown"
selectedValue={props.values.value}
onValueChange={(itemValue) => {
props.setFieldValue("value", itemValue);
setValue(itemValue);
}}
>
<Picker.Item
label="Account"
value={initialValues.value}
key={0}
color="#afb8bb"
/>
{values.map((value, index) => (
<Picker.Item label={value} value={value} key={index} />
))}
</Picker>
</View>
<View style={styles.inputValue}>
<TextInput
style={styles.inputName}
placeholder="Value"
keyboardType="numeric"
onChangeText={props.handleChange("amount")}
value={props.values.amount}
onBlur={props.handleBlur("amount")}
/>
</View>
</View>
<View style={styles.doubleArrow}>
<Entypo name="arrow-long-down" size={40} color="#afb8bb" />
<Entypo name="arrow-long-down" size={40} color="#afb8bb" />
</View>
<View style={styles.box}>
<View style={styles.picker}>
<Picker
mode="dropdown"
selectedValue={props.values.valueTwo}
onValueChange={(itemValue) => {
props.setFieldValue("valueTwo", itemValue);
setValue(itemValue);
}}
>
<Picker.Item
label="Account"
value={initialValues.valueTwo}
key={0}
color="#afb8bb"
/>
{valuesTwo.map((value, index) => (
<Picker.Item label={value} value={value} key={index} />
))}
</Picker>
</View>
<View style={styles.Calendar}><DatePiker /></View>
<View style={styles.inputValue}>
<TextInput
style={styles.inputName}
placeholder="Notes"
multiline= {true}
onChangeText={props.handleChange("notes")}
value={props.values.notes}
onBlur={props.handleBlur("notes")}
/>
</View>
</View>
<SubmitButton title="Save" onPress={props.handleSubmit} />
</View>
</ScrollView>
</Fragment>
)}
</Formik>
</Modal>
);
}
const styles = StyleSheet.create({
headerText: {
fontSize: 20,
marginLeft: 5,
},
container: {
flex: 1,
},
box: {
borderColor: "#afb8bb",
margin: 20,
flexDirection: "column",
borderWidth: 1,
borderStyle: "dashed",
borderRadius:5,
marginTop:40,
},
inputName:{
padding:10,
borderWidth:1,
borderColor:"#afb8bb",
},
inputValue:{
margin:10,
marginHorizontal:20,
},
picker:{
borderWidth:1,
borderColor:"#afb8bb",
margin:10,
marginHorizontal:20,
},
doubleArrow:{
flexDirection:'row',
alignContent:'center',
justifyContent:'center',
marginTop:10
},
Calendar: {
marginTop:-20,
borderColor: "#afb8bb",
paddingVertical: 10,
marginHorizontal:20,
fontSize: 20,
textAlign: 'center',
color: 'black',
}
});

Why is React Native App.js navigation undefined in App.js?

export default function App ({navigation})
There is a function that starts with and contains <Stack.Navigator>.
But when I want to use the navigation feature and use "navigation.navigate ('Lead') in onPress
TypeError: undefined is not an object evaluating react navigation
I get an error. My English is not very good. Please help me on this topic. Now I'm adding the sample codes to you.
import * as React from 'react';
import { StyleSheet, AsyncStorage, Alert, View, Image, TouchableOpacity } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import { ApplicationProvider, Layout, Input, Button, Text, Spinner, IconRegistry, Icon } from '#ui-kitten/components';
import { EvaIconsPack } from '#ui-kitten/eva-icons';
import * as eva from '#eva-design/eva';
import LinkingConfiguration from './navigation/LinkingConfiguration';
import * as axios from 'axios';
import Base64 from './components/Base64';
import LeadScreen from './screens/LeadScreen';
import AddLeadScreen from './screens/AddLeadScreen';
import TabBarIcon from './components/TabBarIcon';
import HomeScreen from './screens/HomeScreen';
import CampaignsScreen from './screens/CampaignsScreen';
import MenuScreen from './screens/MenuScreen';
const Stack = createStackNavigator();
export default function App({ navigation }) {
const logout = async () => {
await AsyncStorage.removeItem('token');
dispatch({ type: 'SIGN_OUT' });
};
return (
<>
<IconRegistry icons={EvaIconsPack} />
<ApplicationProvider {...eva} theme={eva.light}>
<Layout style={styles.container}>
<AuthContext.Provider value={authContext}>
<NavigationContainer linking={LinkingConfiguration}>
<Stack.Navigator>
{state.isLoading ? (
// We haven't finished checking for the token yet
<Stack.Screen name="Splash" component={SplashScreen} options={{ headerShown: false }} />
) : state.token == null ? (
// No token found, user isn't signed in
<>
<Stack.Screen name="Login" component={LoginScreen} options={{ title: 'Oturum Açın' }} />
</>
) : (
// User is signed in
<>
<Stack.Screen name="User" component={UserScreen} options={{
headerStyle: { backgroundColor: '#e8a200' },
headerTintColor: 'white',
headerTitleStyle: { color: '#fff' },
headerRight: () => (
<TouchableOpacity activeOpacity={0.4} underlayColor='transparent' onPress={() => logout() } style={{ marginRight: 12 }}>
<Icon
style={styles.icon}
fill='#FFFFFF'
name='power-outline'
/>
</TouchableOpacity>
)
}} />
<Stack.Screen name="Lead" component={LeadScreen} options={{
title: 'Müşteri Adayları',
headerStyle: { backgroundColor: '#e8a200' },
headerTintColor: 'white',
headerTitleStyle: { fontWeight: 'bold', color: '#fff' },
headerRight: () => (
<TouchableOpacity activeOpacity={0.4} underlayColor='transparent' onPress={ () => console.log(navigation) } style={{ marginRight: 12 }}>
<Icon
style={styles.icon}
fill='#FFFFFF'
name='plus-outline'
/>
</TouchableOpacity>
)}} />
<Stack.Screen name="AddLead" component={AddLeadScreen} options={{ title: 'Müşteri Adayı Ekle' }} />
</>
)}
</Stack.Navigator>
</NavigationContainer>
</AuthContext.Provider>
</Layout>
</ApplicationProvider>
</>
);
}
You can pass the navigation or rout prop into options in the stack.screen like this
options={({navigation})=>({
'Your code here'
})}
I have edited it with your code for you.
<Stack.Screen name="Lead" component={LeadScreen}
options={({ navigation }) => ({
title: 'Müşteri Adayları',
headerStyle: { backgroundColor: '#e8a200' },
headerTintColor: 'white',
headerTitleStyle: { fontWeight: 'bold', color: '#fff' },
headerRight: () => (
<TouchableOpacity activeOpacity={0.4}
underlayColor='transparent' onPress={() =>
console.log(navigation)} style={{ marginRight: 12 }}>
<Icon
style={styles.icon}
fill='#FFFFFF'
name='plus-outline'
/>
</TouchableOpacity>
)
})} />
First, I think the navigation here is unnecessary, you can remove it.
export default function App({ navigation }) {
In your screen components, ie. UserScreen, you can use navigation like so
function UserScreen({navigation}) {
// ...some codes
navigation.navigate('WHERE_TO_GO');
// ...some other codes
}
You could also use navigation without passing it to the props.
First you need to import useNavigation
import { useNavigation } from '#'react-navigation/native'
And then, in your component
function UserScreen() {
const nav = useNavigation();
// ...some codes
nav.navigate('WHERE_TO_GO');
// ...some other codes
}
You could get more details here https://reactnavigation.org/docs/use-navigation/
For the onPress function of Lead screen,
<Stack.Screen name="Lead" component={LeadScreen} options={({ navigation }) => ({
title: 'Müşteri Adayları',
headerStyle: { backgroundColor: '#e8a200' },
headerTintColor: 'white',
headerTitleStyle: { fontWeight: 'bold', color: '#fff' },
headerRight: () => (
<TouchableOpacity activeOpacity={0.4} underlayColor='transparent' onPress={ () => navigation.navigate('WHERE_TO_GO') } style={{ marginRight: 12 }}>
<Icon
style={styles.icon}
fill='#FFFFFF'
name='plus-outline'
/>
</TouchableOpacity>
)})} />
You should use useLinkProps to solve this issue:
import { useLinkProps } from '#react-navigation/stack';
And this is an example on how to write code which uses it:
const LinkButton = ({ to, action, children, ...rest }) => {
const { onPress, ...props } = useLinkProps({ to, action });
I have tried everything but this worked for me.
Make a function in your app.js and pass props then access using props.navigation like below.
function CustomDrawerContent**(props)** {
.....
logOut = () => {
AsyncStorage.clear();
**props.navigation.navigate("Login");**
};
.....
}

ReferenceError: Can't find variable: navigation

So what I'm trying to do is that I'd like the DrawerNavigator to be accessed by selecting the icon on the top left . Im using react nav 5 for this. I keep recieving the error displayed above.
I've tried doing this using this.props.navigation but that also did not seem to work.
Assistance would be greatly appreciared
AppNavigator:
/* eslint-disable no-unused-expressions */
import React, { useState, useEffect } from 'react'
import { NavigationContainer, DrawerActions } from '#react-navigation/native'
import { createStackNavigator } from '#react-navigation/stack'
import auth from '#react-native-firebase/auth'
import {IconButton} from 'react-native-paper'
import Login from '../components/login'
import Signup from '../components/signup'
import forgotPassword from '../components/forgotPassword'
import DashboardScreen from '../screens/DashboardScreen'
const Stack = createStackNavigator()
export default function MyStack() {
// Set state while Firebase Connects
const [starting, setStarting] = useState(true)
const [user, setUser] = useState()
// Handle state changes for user
function onAuthStateChanged(user) {
setUser(user)
if (starting) setStarting(false)
}
useEffect(() => {
const subcriber = auth().onAuthStateChanged(onAuthStateChanged)
return subcriber
// unsub on mount
}, [])
if (starting) return null
if (!user) {
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerTitleAlign: 'center',
headerStyle: {
backgroundColor: '#3740FE',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
}}
>
<>
<Stack.Screen
name="Login"
component={Login}
/>
<Stack.Screen
name="Signup"
component={Signup}
/>
<Stack.Screen
name="ForgotPassword"
component={forgotPassword}
/>
</>
</Stack.Navigator>
</NavigationContainer>
)
}
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerTitleAlign: 'center',
headerStyle: {
backgroundColor: '#3740FE',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
}}
>
<>
<Stack.Screen
name="Dashboard"
component={DashboardScreen}
options={{
headerLeft: props =>
<IconButton
{...props}
icon="menu"
color="white"
onPress={() => navigation.dispatch(DrawerActions.toggleDrawer())}
/>,
headerRight: props =>
<IconButton
{...props}
icon="magnify"
color="white"
/>
}}
/>
</>
</Stack.Navigator>
</NavigationContainer>
)
}
Dashboard:
import 'react-native-paper'
import React from 'react';
import { StyleSheet, View} from 'react-native';
import {Button} from 'react-native-paper'
import { createDrawerNavigator } from '#react-navigation/drawer'
function HomeScreen ({navigation}) {
return (
<View>
<Button
onPress={() => navigation.navigate('Settings')}
/>
</View>
);
}
function SettingsScreen ({navigation}) {
return (
<View> style={styles.container}
<Text>
TESTING
</Text>
</View>
);
}
const Drawer = createDrawerNavigator();
export default function DashboardScreen (){
return (
<Drawer.Navigator initialRouteName="Home">
<Drawer.Screen name="Home" component={HomeScreen}/>
<Drawer.Screen name="Settings" component={SettingsScreen}/>
</Drawer.Navigator>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
display: "flex",
justifyContent: 'center',
alignItems: 'center',
padding: 35,
backgroundColor: '#fff'
},
textStyle: {
fontSize: 15,
marginBottom: 20
}
});
you can get it when you write the options in function like
<Stack.Screen
name="Dashboard"
component={DashboardScreen}
options={({navigation})=>({
headerLeft: props =>
<IconButton
{...props}
icon="menu"
color="white"
onPress={() => navigation.dispatch(DrawerActions.toggleDrawer())}
/>
})}
/>

Navigating by Pressing Images

I am trying to navigate screens by pressing on specific images on SearchScreen.js. Each image leads to a different screen. I am currently trying to navigate from the first image to the screen meo_sw.js. However, I am not being able to do so and I don't undersand why. Here is the code of SearchScreen.js:
import React from 'react';
import { ScrollView, StyleSheet, TextInput, Text, View, Image, TouchableOpacity, TouchableWithoutFeedback} from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
function SearchScreen() {
return (
<View style={styles.screen}>
<View style={styles.container}>
<TextInput style={styles.inputBox}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Procura aqui"
placeholderTextColor = "black"
selectionColor="black"
keyboardType="default"/>
</View>
<View style={styles.teste}>
<Text style={styles.festivais}>Recomendados</Text>
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={styles.festivais_lista}>
<TouchableOpacity onPress={() => navigate('meo_sw')}>
<Image source={require('../assets/images/meo_sudoeste.png')} style={styles.image}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('vodaf_coura')}>
<Image source={require('../assets/images/vodafone_coura.png')} style={styles.image} />
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('superR_superB')}>
<Image source={require('../assets/images/superbock_superrock.png')} style={styles.image}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('nos_primavera')}>
<Image source={require('../assets/images/nos_primavera.png')} style={styles.image}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('rock_in_rio')}>
<Image source={require('../assets/images/rock_in_rio.png')} style={styles.image}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('edp_cool_jazz')}>
<Image source={require('../assets/images/edp_cooljazz.png')} style={styles.image}/>
</TouchableOpacity>
</ScrollView>
</View>
</View>
);
}
SearchScreen.navigationOptions = {
title: 'Procurar',
};
const styles = StyleSheet.create({
//I took this off because it's irrelevant for the question itself
});
export default SearchScreen;
And here is the screen 'meo_sw.js':
import React from 'react';
import {View, Text, TouchableOpacity, StyleSheet} from 'react-native';
const meo_sw = props => {
return(
<View style={styles.header}>
<Text style={styles.texto}>Meo Sudoeste</Text>
</View>
)
};
const styles=StyleSheet.create({
//Irrelevant
})
export default meo_sw;
The error says simply:
ReferenceError: Can't find variable: navigate
Please help me
UPDATED
This is the MainTabNavigator.js:
import React from 'react';
import { Platform } from 'react-native';
import { createStackNavigator } from 'react-navigation-stack';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import TabBarIcon from '../components/TabBarIcon';
import HomeScreen from '../screens/HomeScreen';
import SearchScreen from '../screens/SearchScreen';
import SettingsScreen from '../screens/SettingsScreen';
import ChatScreen from '../screens/ChatScreen';
import CalendarScreen from '../screens/CalendarScreen';
import meo_sw from '../Eventos/Festivais/meo_sw';
const config = Platform.select({
web: { headerMode: 'screen' },
default: {},
});
//Home
const HomeStack = createStackNavigator(
{
HomeScreen: {screen: HomeScreen},
SearchScreen: {screen: SearchScreen},
ChatScreen: {screen: ChatScreen},
SettingsScreen: {screen: SettingsScreen},
CalendarScreen: {screen: CalendarScreen},
},
config
);
HomeStack.navigationOptions = {
tabBarLabel: 'Home',
tabBarIcon: ({ focused }) => (
<TabBarIcon
focused={focused}
name={
Platform.OS === 'ios'
? `ios-home${focused ? '' : '-outline'}`
: 'md-home'
}
/>
),
};
HomeStack.path = '';
//Search
const SearchStack = createStackNavigator(
{
Search: SearchScreen,
},
config
);
SearchStack.navigationOptions = {
tabBarLabel: 'Procurar',
tabBarIcon: ({ focused }) => (
<TabBarIcon focused={focused} name={Platform.OS === 'ios' ? 'ios-search' : 'md-search'} />
),
};
SearchStack.path = '';
//Chat
const ChatStack = createStackNavigator(
{
Chat: ChatScreen,
},
config
);
ChatStack.navigationOptions = {
tabBarLabel: 'Chat',
tabBarIcon: ({ focused }) => (
<TabBarIcon
focused={focused}
name={
Platform.OS === 'ios'
? `ios-chatboxes${focused ? '' : '-outline'}`
: 'md-chatboxes'
}
/>
),
};
ChatStack.path = '';
//Settings
const SettingsStack = createStackNavigator(
{
Settings: SettingsScreen,
},
config
);
SettingsStack.navigationOptions = {
tabBarLabel: 'Perfil',
tabBarIcon: ({ focused }) => (
<TabBarIcon focused={focused} name={Platform.OS === 'ios' ? 'ios-person' : 'md-person'} />
),
};
SettingsStack.path = '';
//Calendar
const CalendarStack = createStackNavigator(
{
Calendar: CalendarScreen,
},
config
);
CalendarStack.navigationOptions = {
tabBarLabel: 'Calendário',
tabBarIcon: ({ focused }) => (
<TabBarIcon focused={focused} name={Platform.OS === 'ios' ? 'ios-calendar' : 'md-calendar'} />
),
};
CalendarStack.path = '';
//Bottom tab navigator
const tabNavigator = createBottomTabNavigator({
SearchStack,
CalendarStack,
HomeStack,
ChatStack,
SettingsStack
});
tabNavigator.path = '';
export default tabNavigator;
And this is the AppNavigator.js:
import React from 'react';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import MainTabNavigator from './MainTabNavigator';
export default createAppContainer(
createSwitchNavigator({
Main: MainTabNavigator,
})
);
Pass navigation object as prop.
function SearchScreen({ navigation }) {
....
}
The use it like
<TouchableOpacity onPress={() => navigation.navigate('meo_sw')}>
<Image source={require('../assets/images/meo_sudoeste.png')} style={styles.image}/>
</TouchableOpacity>
Add the screen to one of your navigators, like the following.
const HomeStack = createStackNavigator(
{
HomeScreen: { screen: HomeScreen },
SearchScreen: { screen: SearchScreen },
ChatScreen: { screen: ChatScreen },
SettingsScreen: { screen: SettingsScreen },
CalendarScreen: { screen: CalendarScreen },
meo_sw: { screen: meo_sw}
},
config
);
HomeStack.navigationOptions = {
tabBarLabel: 'Home',
tabBarIcon: ({ focused }) => (
<TabBarIcon
focused={focused}
name={
Platform.OS === 'ios'
? `ios-home${focused ? '' : '-outline'}`
: 'md-home'
}
/>
),
};
Expo example
your Function is unable to get the props so that its not importing navigation property !!
change the function into class and get the props in class and then try navigating.
try this code
export default class SearchScreen extends Component {
constructor(props) {
super(props);
this.state = { }
}
return (
<View style={styles.screen}>
<View style={styles.container}>
<TextInput style={styles.inputBox}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Procura aqui"
placeholderTextColor = "black"
selectionColor="black"
keyboardType="default"/>
</View>
<View style={styles.teste}>
<Text style={styles.festivais}>Recomendados</Text>
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false} style={styles.festivais_lista}>
<TouchableOpacity onPress={() => this.props.navigation.navigate('meo_sw')}>
<Image source={require('../assets/images/meo_sudoeste.png')} style={styles.image}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('vodaf_coura')}>
<Image source={require('../assets/images/vodafone_coura.png')} style={styles.image} />
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('superR_superB')}>
<Image source={require('../assets/images/superbock_superrock.png')} style={styles.image}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('nos_primavera')}>
<Image source={require('../assets/images/nos_primavera.png')} style={styles.image}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('rock_in_rio')}>
<Image source={require('../assets/images/rock_in_rio.png')} style={styles.image}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('edp_cool_jazz')}>
<Image source={require('../assets/images/edp_cooljazz.png')} style={styles.image}/>
</TouchableOpacity>
</ScrollView>
</View>
</View>
);
}
Hope it helps , feel free for doubts.

Categories

Resources