How to open a modal in drawer headerRight icon button? - javascript

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',
}
});

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'},
]

Components display perfectly on web view but aren't being displayed on android view in React Native

I'm building an instagram clone using React Native with Homescreen consisting of custom Header and Imagepost components,but it isn't showing up properly on android although it displays perfectly on web view(images below).
I only added the Text and the Test Button for testing purposes
HomeScreen.js:
import React, { useEffect, useState } from "react";
import { View, Text, TouchableOpacity, Button } from "react-native";
import axios from "axios";
import ImagePost from "../../components/ImagePost";
import Header from "../../components/Header";
import Ionicons from "react-native-vector-icons/Ionicons";
import useStore from "../../store";
const HomeScreen = ({ navigation }) => {
const [posts, setposts] = useState([]);
const [current, setcurrent] = useState(null);
const user = useStore((state) => state.currentUser);
const setcurrentUser = useStore((state) => state.setcurrentUser);
useEffect(() => {
axios.get("http://localhost:5000/posts").then((response) => {
console.log(response.data.posts);
setposts(response.data.posts);
});
}, []);
return (
<View>
<Header navigation={navigation} />
<Text>huidhoasodhiohdp</Text>
<Button title="test" />
{console.log("now user", user)}
{console.log("posts", posts)}
{posts &&
posts.map((post) => {
return (
<View key={post._id}>
<ImagePost post={post} navigation={navigation} />
{console.log("This post is", post)}
</View>
);
})}
</View>
);
};
export default HomeScreen;
Header.js:
import React from "react";
import { View, TouchableOpacity, Text } from "react-native";
import Ionicons from "react-native-vector-icons/Ionicons";
import useStore from "../store";
const Header = ({ navigation }) => {
console.log("header navigation", navigation);
const user = useStore((state) => state.currentUser);
return (
<View
style={{
flex: 1,
flexDirection: "row",
justifyContent: "space-between",
backgroundColor: "white",
}}
>
<TouchableOpacity
onPress={() => navigation.navigate("AddScreen")}
style={{ margin: "5%" }}
>
<Ionicons name="add-outline" size={25} color="black" />
</TouchableOpacity>
{user && <Text>{user.username}</Text>}
{user && console.log(user.username)}
<TouchableOpacity style={{ margin: "5%" }}>
<Ionicons name="chatbubble-ellipses-outline" size={25} color="black" />
</TouchableOpacity>
</View>
);
};
export default Header;
ImagePost.js :
import React from "react";
import { View, Text, Image, TouchableOpacity, Button } from "react-native";
import Ionicons from "react-native-vector-icons/Ionicons";
const ImagePost = ({ post, navigation }) => {
return (
<View>
<View style={{ flex: 1, flexDirection: "row", alignItems: "center" }}>
<Image
style={{
width: 50,
height: 50,
borderRadius: 50,
marginRight: "3%",
}}
source={post.creator.pic}
/>
<Text style={{ fontWeight: "bold" }}>User</Text>
</View>
<View style={{ width: "100%", height: 450 }}>
<Image
style={{ resizeMode: "cover", height: "100%" }}
source={post.file}
/>
<View style={{ flex: 1, flexDirection: "row", marginBottom: "6%" }}>
<TouchableOpacity style={{ marginRight: "1%" }}>
<Ionicons name="heart-outline" size={25} color="black" />
</TouchableOpacity>
<TouchableOpacity
style={{ marginRight: "1%" }}
onPress={() =>
navigation.navigate("CommentsScreen", { postId: post._id })
}
>
<Ionicons name="chatbubble-outline" size={25} color="black" />
</TouchableOpacity>
</View>
<Text>
<Text style={{ fontWeight: "bold", marginRight: "5%" }}>
{post.creator.userName}
</Text>
{post.description}
</Text>
</View>
</View>
);
};
export default ImagePost;
Android view
Web view

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

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.

React Native: Unable to navigate to the' Login.js' screen

I have created 3 files and places the navigation container in the app.js file. i am unable to navigate through the screens. I don't understand where the mistake lies.
App.js
import 'react-native-gesture-handler';
import React, { useState } from 'react';
import { NavigationContainer } from '#react-navigation/native';
import Login from './Login.js';
import {createStackNavigator} from '#react-navigation/stack';
import InitialScreen from './InitialScreen.js';
const Stack = createStackNavigator();
function Nav() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="InitialScreen">
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="InitialScreen" component={InitialScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default Nav;
InitialScreen.js
import 'react-native-gesture-handler';
import React, { useState } from 'react';
import {Button, Text, TextInput, View, StyleSheet ,TouchableOpacity,Image} from 'react-native';
import Icon from 'react-native-vector-icons/Feather';
import { NavigationContainer } from '#react-navigation/native';
import Login from './Login.js';
function InitialScreen({navigation}){
const pressHandler=()=>{
navigation.navigate('Login');
}
return (
<>
<View style={styles.container}>
<View style={styles.Container0}>
<TouchableOpacity>
<Text style={{backgroundColor:'white',
fontSize:30,
borderWidth:2,
borderRadius:4,
marginTop: 5,
marginLeft:10,
marginRight:10,
fontWeight:'bold',
textAlign:'center',
padding:2,
}} onPress={pressHandler}
>Login</Text>
<Text style={{marginLeft:10,
fontSize:15,}}> Do not have an account?</Text>
<Text style={{backgroundColor:'white',
fontSize:30,
borderWidth:2,
borderRadius:4,
marginTop: 5,
marginLeft:10,
marginRight:10,
fontWeight:'bold',
textAlign:'center',
padding:2,
}}>SignUp</Text>
</TouchableOpacity>
</View>
<View style={styles.Container1}>
<Image source={{uri: 'http://i.pinimg.com/originals/d1/9b/4d/d19b4d524b8f95b3c640228c28373696.jpg'}}
style={{width:'100%',
height:'100%',
marginTop:5,
flexDirection: 'column',
justifyContent: 'center',
alignSelf: 'center',}}/>
</View>
<View style={styles.Container3}>
<Text style={{fontSize:25,fontWeight:'bold',
color:'white',
textAlign:'center',
}}>I am going to be so productive!!!!!!</Text>
</View>
</View>
<View style={styles.icons}>
<Icon
name='download-cloud'
size={30}
/>
<Icon
name='mail'
size={30}
/>
<Icon
name='instagram'
size={30}
/>
<Icon
name='link'
size={30}
/>
</View>
</>
);
}
const styles=StyleSheet.create({
container:
{ flex:0.9,
marginLeft:5,
marginRight:5,
marginTop:5,
marginBottom:5,
backgroundColor:'black',
},
Container0:
{ flex:0.25,
flexDirection:'column',
backgroundColor:'#ffa07a',
},
Container1:
{
flex:0.6,
backgroundColor:'white',
},
Container3:
{flex:0.1,
justifyContent:"center",
alignItems:'center',
marginTop:10,
},
icons:
{
flex:0.1,
flexDirection: 'row',
justifyContent:'space-around',
marginTop:10,
},
}
);
export default InitialScreen;
Login.js
import 'react-native-gesture-handler';
import React, { useState } from 'react';
import { Text, TextInput, View, StyleSheet ,TouchableOpacity,Image} from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
function Login() {
const [text,onChangeText]= React.useState('Enter your email');
const [Value,setValue]= React.useState('Enter your password');
return(
<View style={styles.container}>
<Text style={{marginTop:40,fontWeight:'bold',fontSize:40,textAlign:'center',}}>Login</Text>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={text => onChangeText(text)}
value={value}
/>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
setValue={Value => setValue(Value)}
value={value}
/>
</View>
);
}
const styles=StyleSheet.create({
container:
{
flexDirection:'column',
}
});
export default Login;
I don't understand why the "onPress" isn't working here . I am unable to even click on it . it is just like a text with no response or change in opacity too . The navigation isn't working either.
#nandita you are using onPress on Text tag. onPress event only works on TouchableOpacity or TouchableHightlight
try doing this.
<TouchableOpacity onPress={pressHandler}>
<Text style={{backgroundColor:'white',
fontSize:30,
borderWidth:2,
borderRadius:4,
marginTop: 5,
marginLeft:10,
marginRight:10,
fontWeight:'bold',
textAlign:'center',
padding:2,
}}
>Login</Text>
<TouchableOpacity>

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())}
/>
})}
/>

Categories

Resources