When Using react-navigation version 4.1.1
When navigating from one screen to another screen it is fluctuating and i am using ImageBackground there ,so first white blank screen appears after that imagebackground is loading which is very slow and i can easily see the transition over there .
I dont know what's the exact issue is there.
And for this new version i have to install libraries also for react navigation i.e.react-native screens,animated and maskedView ,safeareacontext.
So please any one know about this please let me know ..
Thanks in advance .
Here is a video for my app where i am getting image loading issue...
https://drive.google.com/open?id=16bdmxOC342uCQl3UL_hB8K0wznpbedge
Here is my APP.js File where i have created stack navigator..
import React, { Component } from 'react';
import { createAppContainer } from "react-navigation"
import { createStackNavigator } from 'react-navigation-stack';
import WelcomeScreen from './Screens/WelcomeScreen';
import Walkthorugh from './Screens/Walkthrough';
import Login from './Screens/Login';
import Signup from './Screens/Signup';
import Profile from './Screens/Profile';
import Wishlist from './Screens/Wishlish';
import Home from './Screens/Home';
import Cart from './Screens/Cart';
const notificationsel = require('./Screens/icons/notificationsel.png');
import { createBottomTabNavigator } from 'react-navigation-tabs';
import { enableScreens } from 'react-native-screens';
import { useScreens } from 'react-native-screens';
import {
StyleSheet,
Easing,
View, Animated, FlatList,
Text, Image, Alert, YellowBox, Button, ImageBackground,
TouchableWithoutFeedback, TouchableOpacity
} from 'react-native';
const welcomeStack = createStackNavigator({
Welcome:{screen:WelcomeScreen
},
});
const homeStack = createStackNavigator({
Home:{screen:Home
},
});
const profileStack = createStackNavigator({
Profile:{screen:Profile,
navigationOptions:{header:null}},
});
const cartStack = createStackNavigator({
Cart:{screen:Cart,
navigationOptions:{header:null}},
});
const wishlistStack = createStackNavigator({
Wishlist:{screen:Wishlist,
navigationOptions:{header:null}},
});
const HomeTabNavigator = createBottomTabNavigator({
Home : homeStack,
Profile : profileStack,
Cart : cartStack,
Wishlist : wishlistStack,
},
{
defaultNavigationOptions: ({ navigation }) => ({
tabBarOnPress: ({ navigation, defaultHandler }) => {
console.log('onPress:', navigation.state.routeName);
// if(navigation.state.routeName=='CallNow'){
// Linking.openURL(`tel:${'9414036555'}`)
// console.log("CallNow")
// }
defaultHandler()
},
tabBarIcon: ({ focused, horizontal, tintColor }) => {
const { routeName } = navigation.state;
let iconName;
if (routeName === 'Home') {
iconName = focused ? notificationsel : notificationsel;
}
else if (routeName === 'Profile') {
iconName = focused ? notificationsel : notificationsel;
}
else if (routeName === 'Cart') {
iconName = focused ? notificationsel : notificationsel;
}
else if (routeName === 'Wishlist') {
iconName = focused ? notificationsel : notificationsel;
}
// You can return any component that you like here!
return <Image source={iconName} style={{width:22,height:22}}/>
;
},
}),
tabBarOptions:{
activeTintColor: 'blue',
inactiveTintColor: '#000',
showLabel:true,
style:{backgroundColor:'#fff',padding:5}
},
}
);
const AppNavigator = createStackNavigator(
{
Home: {
screen: HomeTabNavigator,
// navigationOptions:{header:null}
},
Walkthorugh:{
screen:Walkthorugh,
// navigationOptions:{header:null}
},
Welcome:{
screen:WelcomeScreen,
// navigationOptions:{header:null}
},
Login:{
screen:Login,
},
Signup:{
screen:Signup,
// navigationOptions:{header:null}
},
},
{
headerMode:'none',
initialRouteName: "Walkthorugh",
cardStyle: {backgroundColor: "transparent", opacity: 1 },
defaultNavigationOptions: {
gesturesEnabled: false,
cardStyle: {backgroundColor: "transparent", opacity: 1 },
swipeEnabled: false,
animationEnabled: false,
},
}
);
const AppContainer = createAppContainer(AppNavigator);
export default class App extends Component {
render() {
return (
<AppContainer />
)
}
}
And this is my Login.js ..
import React, { Component } from 'react';
import {
StyleSheet,
Platform,
View, ActivityIndicator, FlatList,
Text, Image, Dimensions, Keyboard, TextInput, ImageBackground,
StatusBar, TouchableOpacity
} from 'react-native';
import { NavigationActions, StackActions } from 'react-navigation';
const { width, height } = Dimensions.get('window');
const app_icon = require('./icons/app_icon.png')
const loginbg = require('./icons/loginbg.jpg')
const fashionbot = require('./icons/fashionbot.png')
import { Api_const, App_colors } from './Const/Const.js';
import { ScrollView } from 'react-native-gesture-handler';
import LinearGradient from 'react-native-linear-gradient';
export default class Login extends Component {
static navigationOptions = {
headerTitle: 'Login',
// headerLeft: (
// <View style={{ flexDirection: "row", marginLeft: 20, marginRight: 20 }}>
// <TouchableWithoutFeedback>
// <Image source={require('../assets/Hamburger.png')} >
// </Image>
// </TouchableWithoutFeedback>
// </View>
// ),
headerStyle: { borderBottomWidth: 0, marginTop: (Platform.OS === 'ios') ? 0 : 0 },
headerBackTitle: " "
};
constructor(props) {
super(props);
this.state = {
isLoading: false,
email: '',
password: '',
}
}
onClick_Login = () => {
var action = StackActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: 'Home',params:{test:'test'} })]
});
this.props.navigation.dispatch(action);
// setTimeout(()=>{
// this.props.navigation.dispatch(action);
// },
// 400);
}
render() {
if (this.state.isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" />
</View>
);
}
return (
<LinearGradient colors={[App_colors.purple, App_colors.pink, App_colors.pink]} style={{flex:1}}>
<ScrollView ref="scrollView" style={{ flex:1 }} bounces={false}>
<StatusBar hidden={true} backgroundColor={App_colors.purple} barStyle="dark-content" />
<View style={{ flex:1,height}}>
<ImageBackground source={loginbg} style={{height }}>
<View style={{height }}>
<View style={{ flexDirection: 'row', margin: 15 }}>
<Image style={{ flex: 0.3, height: 90, alignItems: 'center', justifyContent: 'center', alignSelf: 'center' }} resizeMode={"contain"} source={app_icon} />
<Image style={{ flex: 1, alignItems: 'center', justifyContent: 'center', alignSelf: 'center' }} resizeMode={"contain"} source={fashionbot} />
</View>
<View style={{flex:1, justifyContent: 'center', marginLeft: 25, marginRight: 25 }}>
<Text style={{ fontSize: 22, color: '#fff', alignItems: 'center', alignSelf: 'center' }}>{'Login'}</Text>
<Text style={{ fontSize: 16, color: '#fff', marginTop: 15 }}>{'Email'}</Text>
<TextInput style={{ fontSize: 14, height: 40, marginLeft: 0, marginRight: 0, color: 'white' }}
value={this.state.email}
onChangeText={(text) => this.setState({ email: text })}
placeholder={'Your Email'}
placeholderTextColor={App_colors.white}
underlineColorAndroid={'white'}
textContentType={'username'}
keyboardType='email-address'
caretHidden={false}
onSubmitEditing={() => { Keyboard.dismiss() }}
/>
{/* PASSWORD */}
<Text style={{ fontSize: 16, color: '#fff', marginTop: 15 }}>{'Password'}</Text>
<TextInput style={{ fontSize: 14, height: 40, marginLeft: 0, marginRight: 0, color: 'white' }}
value={this.state.password}
onChangeText={(text) => this.setState({ password: text })}
placeholder={'*********'}
placeholderTextColor={App_colors.white}
underlineColorAndroid={'white'}
secureTextEntry={true}
caretHidden={false}
onSubmitEditing={() => { Keyboard.dismiss() }}
/>
<Text style={{ fontSize: 16, color: '#fff', marginTop: 5 }}>{'Forgot Password?'}</Text>
<TouchableOpacity style={{ justifyContent: 'center',alignSelf:'center', marginBottom: 10, marginTop: 30, width: width - 100, marginLeft: 0, marginRight: 0, alignItems: 'center', borderRadius: 25, borderWidth: 0, paddingTop: 15, paddingBottom: 15, backgroundColor: 'white' }}
onPress={this.onClick_Login}>
<Text style={{ fontSize: 16, color: App_colors.purple }}>{'Log in'}</Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>
</View>
</ScrollView>
</LinearGradient>
);
}
}
in development mode react-native will show white screen. But in production, it won't so don't worry. it is normal.
about navigation I can't be sure but share the code or demo(image/video).
Related
I have to add DarkMode switch to one of the Screen which applies to all the screen in React Native IOS App.
Below is the App.js where I wrap my main navigator inside ThemeProvider
import React from 'react';
import {Provider} from 'react-redux';
import {createStore, combineReducers,applyMiddleware} from 'redux';
import ReduxThunk from 'redux-thunk';
import authReducer from './store/reducers/auth';
import deviceReducer from './store/reducers/device';
import FR_Navigator from './navigation/FR_Navigator';
import downloadReducer from './store/reducers/download';
import { RootSiblingParent } from 'react-native-root-siblings';
import { ThemeProvider} from './theme/theme-context';
const rootReducer = combineReducers({
auth: authReducer,
download:downloadReducer,
device:deviceReducer
});
const store = createStore(rootReducer,applyMiddleware(ReduxThunk));
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<ThemeProvider>
<FR_Navigator />
</ThemeProvider>
</Provider>
);
}
}
Below is the FRNavigator which has Settings Page which sets DarkMode.
FRNavigator.js
import React from 'react';
import { View,StyleSheet,SafeAreaView,Button,ScrollView,Text} from 'react-native';
import { createSwitchNavigator,createAppContainer } from 'react-navigation';
import {createStackNavigator,StackViewTransitionConfigs} from 'react-navigation-
stack';
import MainPage from '../screens/FaceRecog/MainPage';
import UploadPage from '../screens/FaceRecog/UploadPage';
import { createDrawerNavigator,DrawerItems} from 'react-navigation-drawer';
import Icon from 'react-native-vector-icons/Ionicons';
import DownloadPage from '../screens/FaceRecog/DownloadPage';
import RateUsScreen from '../screens/FaceRecog/RateUsScreen';
import ForgotPasswordScreen from '../screens/UI/ForgotPasswordScreen';
import ImageBrowserScreen from '../screens/FaceRecog/ImageBrowserScreen';
import LoginScreen from '../screens/UI/LoginScreen';
import RegisterScreen from '../screens/UI/Register';
import AddDevicePage from '../screens/FaceRecog/AddDevicePage';
import LogoutComponent from '../components/FaceRecog/LogoutComponent'
import DrawerHeader from '../components/FaceRecog/DrawerHeader';
import CommunicateComponent from '../components/FaceRecog/CommunicateComponent';
import ManageDevice from '../screens/FaceRecog/ManageDevicePage';
import Register from '../screens/UI/Register';
import Settings from '../screens/FaceRecog/Settings';
const AuthNavigator = createStackNavigator(
{
Login:
{
screen:LoginScreen,
navigationOptions: {
headerShown: false,
}
},
SignUp:
{
screen:Register
},
ForgotPasswordPage:
{
screen:ForgotPasswordScreen,
navigationOptions: {
headerShown: true,
}
}
},
);
const MainPageNavigator = createStackNavigator({
Home:MainPage,
AddDevice:AddDevicePage,
Upload:UploadPage,
ImagePicker:ImageBrowserScreen,
ManageDev:ManageDevice,
Setting:
{
screen:Settings,
transitionConfig: () => StackViewTransitionConfigs.SlideFromRightIOS,
},
RateUs:RateUsScreen,
})
const DrawerNavigator = createDrawerNavigator(
{
Home:
{
screen:MainPageNavigator,
navigationOptions:{
drawerIcon:(
<Icon
name='md-home-sharp' size={25} color='grey'/>
)
}
},
Download:
{
screen:DownloadPage,
navigationOptions:{
drawerIcon:(
<Icon
name='md-download'
type='ionicons' size={25} color='grey'onPress={ () => {
}}/>
)
}
},
Exit:
{
screen:Register,
navigationOptions:{
drawerIcon:(
<Icon
name='exit-outline'
type='ionicons' size={25} color='grey' onPress={ () => {
}}/>
)
}
}
},
{
contentOptions:{
activeTintColor: '#e91e63',
},
contentComponent: (props) =>
<ScrollView>
<SafeAreaView style={{flex:1}} forceInset={{ top: 'always', horizontal: 'never',
height:180 }}>
<View style={{width:'100%', backgroundColor: 'white', }}>
<DrawerHeader />
</View>
<DrawerItems {...props} />
<LogoutComponent />
<View
style={{
borderBottomColor: 'grey',
borderBottomWidth: 1
}}/>
<View style={styles.communicateview}>
<Text style={styles.communicatetext}>Communicate</Text>
<CommunicateComponent {...props}/>
</View>
</SafeAreaView>
</ScrollView>,
},
);
const MainNavigator = createSwitchNavigator({
Auth: AuthNavigator,
App:DrawerNavigator
});
const styles = StyleSheet.create({
communicatetext:{
fontWeight:'800',
color:'grey'
},
communicateview:{
top:'3%',
left:'3%'
}
})
export default createAppContainer(MainNavigator);
Below is the Settings Page where I have added Toggle button to set DarkMode:
Settings.js
import React,{useState,useContext} from 'react';
import { View, StyleSheet ,Text,Switch,StatusBar,TouchableOpacity,Button} from
'react-native';
import { HeaderButtons, Item } from 'react-navigation-header-buttons';
import HeaderButton from '../../components/UI/HeaderButton';
import Icon from 'react-native-vector-icons/Entypo';
import { ThemeContext } from '../../theme/theme-context';
const Settings = props => {
const { dark, theme, toggle } = useContext(ThemeContext);
return <View style={styles.container}>
<View style={styles.appsettingstextview}>
<Text style={styles.appsettingstext}>App Settings </Text>
<View style={styles.box}>
<View style={{right:80}}>
<Icon name='adjust' type='entypo' size={40} color='#00008B'/>
</View>
<View style={{right:70}}><Text style={{fontWeight:'bold'}}>Dark Mode</Text></View>
<View style={{left:80}}>
<Switch
trackColor={{ false: "#767577", true: "#ccc" }}
thumbColor={dark ? "#fff" : "#f4f3f4"}
onChange={toggle} value = {dark} />
</View>
</View>
</View>
</View>
};
const styles = StyleSheet.create({
container:{
flex:1,paddingTop:40,paddingLeft:20,
paddingBottom: 60
},
apppermissiontextview:{
},
appsettingstext:{
fontSize:17,
color:'#0437F2',
fontWeight:'bold'
},
apppermissiontextview:{
top:'5%',
},
apppermissiontext:{
fontSize:17,
color:'#0437F2',
fontWeight:'bold'
},
box: {
shadowColor: 'rgba(0,0,0, .4)', // IOS
shadowOffset: { height: 1, width: 1 },
shadowOpacity: 1, // IOS
shadowRadius: 1, //IOS
backgroundColor: '#fff',
elevation: 2, // Android
height: 80,
width:380,
borderRadius: 5,
marginVertical: 40,
backgroundColor: "#FFFFFF",
alignItems: "center",
justifyContent: "center",
flexDirection: 'row',
},
text: {
fontSize: 14,
fontWeight: "bold",
margin: 8,
color: "#000",
textAlign: "center"
}
});
Settings.navigationOptions = navData =>{
return{
headerTitle: 'Settings',
headerTitleStyle:{
color:'white',
},
headerTitleAlign:"left",
headerStyle: {
backgroundColor: '#0437F2',
},
headerLeft: () =>
<HeaderButtons HeaderButtonComponent={HeaderButton}>
<Item
//title="Menu"
iconName={'chevron-back-outline'}
onPress={() => {
//navData.navigation.toggleDrawer();
navData.navigation.navigate('Home');
}}
/>
</HeaderButtons>
}
};
export default Settings;
If I run the above program, when I toggle the Switch, nothing happens.Can anyone say how to add the Settings.js Page to work with FRNavigator to support darkmode toggle switch.Thanks in Advance.
I added darkmode style as style={[styles.box,{ backgroundColor: theme.backgroundColor }]}> to the View in the Settings Page and I could get switch between dark and light theme.Below is the Settings code changes I made :
Settings.js:
import React,{useState,useContext} from 'react';
import { View, StyleSheet
,Text,Switch,StatusBar,TouchableOpacity,Button} from 'react-native';
import { HeaderButtons, Item } from 'react-navigation-header-buttons';
import HeaderButton from '../../components/UI/HeaderButton';
import Icon from 'react-native-vector-icons/Entypo';
import { ThemeContext } from '../../theme/theme-context';
const Settings = () => {
const { dark, theme, toggle } = useContext(ThemeContext);
return <View style={styles.container}>
<View style={styles.appsettingstextview}>
<Text style={styles.appsettingstext}>App Settings </Text>
<View style={[styles.box,{ backgroundColor: theme.backgroundColor }]}>
<View style={{right:80}}><Icon
name='adjust'
type='entypo' size={40} color='#00008B'/>
</View>
<View style={{right:70}}><Text style={[styles.darkmodetext,
{color:theme.color}]}>Dark Mode</Text></View>
<View style = {styles.containerSwitch}>
<Switch
trackColor={{ false: "#ccc", true: "#d43790" }}
thumbColor={dark ? "#f5dd4b" : "#f4f3f4"}
ios_backgroundColor="#3e3e3e"
onChange={toggle} value = {dark} />
</View>
</View>
</View>
</View>
};
const styles = StyleSheet.create({
container:{
flex:1,paddingTop:40,paddingLeft:20,
paddingBottom: 60
},
appsettingstext:{
fontSize:17,
color:'#0437F2',
fontWeight:'bold'
},
darkmodetext:{
fontWeight:'bold',
fontSize:18
},
box: {
shadowColor: 'rgba(0,0,0, .4)', // IOS
shadowOffset: { height: 1, width: 1 },
shadowOpacity: 1, // IOS
shadowRadius: 1, //IOS
backgroundColor: '#fff',
elevation: 2, // Android
height: 80,
width:380,
borderRadius: 5,
marginVertical: 40,
backgroundColor: "#FFFFFF",
alignItems: "center",
justifyContent: "center",
flexDirection: 'row',
bottom:'7%'
},
text: {
fontSize: 14,
fontWeight: "bold",
margin: 8,
color: "#000",
textAlign: "center"
},
containerSwitch:{
marginBottom:50,
top:'6%',
left:'110%'
}
});
Settings.navigationOptions = navData =>{
return{
headerTitle: 'Settings',
headerTitleStyle:{
color:'white',
},
headerTitleAlign:"left",
headerStyle: {
backgroundColor: '#0437F2',
},
headerLeft: () =>
<HeaderButtons HeaderButtonComponent={HeaderButton}>
<Item
//title="Menu"
iconName={'chevron-back-outline'}
onPress={() => {
//navData.navigation.toggleDrawer();
navData.navigation.navigate('Home');
}}
/>
</HeaderButtons>
}
};
export default Settings;
I am getting undefined is not an object evaluating _this.props.navigation. Here is my code. I want to use Flatlist to call the screen 'PlaceorderScreen.js' number of times from the component 'NearbyLSP.js' present in the 'HomeScreen.js'. Also I had referred many solutions for the above problem but yet I didn't get how to get through it. I am a beginner in react-native, So I had used expo for app development.
HomeScreen.js
import React from "react";
import {
View,
Text,
StyleSheet,
SafeAreaView,
TextInput,
Platform,
StatusBar,
ScrollView,
TouchableOpacity,
Dimensions,
Animated,
} from "react-native";
import Icon from 'react-native-vector-icons/Ionicons'
import Category from './Category'
import Expressmode from './Expressmode'
import { FlatList } from "react-native-gesture-handler";
import NearbyLSP from "./NearbyLSP";
const { width } = Dimensions.get('window')
const data = [
{id:'1',name:'LSP1',phone:'1234',email:'abc#gmail.com'},
{id:'2',name:'LSP2',phone:'0234',email:'abc2#gmail.com'},
{id:'3',name:'LSP3',phone:'2234',email:'abc3#gmail.com'}
]
const renderList = ((item) =>{
return <TouchableOpacity
onPress={()=> this.props.navigation.navigate('PlaceOrder')}
activeOpacity={0.7}>
<NearbyLSP name={item.name}/>
</TouchableOpacity>
})
export default class HomeScreen extends React.Component {
componentDidMount() {
this.scrollY = new Animated.Value(0)
this.startHeaderHeight = 80
this.endHeaderHeight = 50
if (Platform.OS == 'android') {
this.startHeaderHeight = 100 + StatusBar.currentHeight
this.endHeaderHeight = 70 + StatusBar.currentHeight
}
this.animatedHeaderHeight = this.scrollY.interpolate({
inputRange: [0, 50],
outputRange: [this.startHeaderHeight, this.endHeaderHeight],
extrapolate: 'clamp'
})
this.animatedOpacity = this.animatedHeaderHeight.interpolate({
inputRange: [this.endHeaderHeight, this.startHeaderHeight],
outputRange: [0, 1],
extrapolate: 'clamp'
})
this.animatedTagTop = this.animatedHeaderHeight.interpolate({
inputRange: [this.endHeaderHeight, this.startHeaderHeight],
outputRange: [-30, 10],
extrapolate: 'clamp'
})
this.animatedMarginTop = this.animatedHeaderHeight.interpolate({
inputRange: [this.endHeaderHeight, this.startHeaderHeight],
outputRange: [50, 30],
extrapolate: 'clamp'
})
}
render() {
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1 }}>
<Animated.View style={{ height: this.animatedHeaderHeight, backgroundColor: 'white', borderBottomWidth: 1, borderBottomColor: '#dddddd' }}>
<View style={{
flexDirection: 'row', padding: 10,
backgroundColor: 'white', marginHorizontal: 10,
shadowOffset: { width: 0, height: 0 },
shadowColor: 'black',
shadowOpacity: 0.2,
elevation: 1,
marginTop: null
}}>
<Icon name="ios-search" size={25} style={{ marginRight: 10 ,marginTop:5 , opacity:0.6}} />
<TextInput
underlineColorAndroid="transparent"
placeholder="Find LSP"
placeholderTextColor="grey"
style={{ flex: 1, fontWeight: '700', backgroundColor: 'white' }}
/>
</View>
</Animated.View>
<ScrollView
scrollEventThrottle={16}
onScroll={Animated.event(
[
{ nativeEvent: { contentOffset: { y: this.scrollY } } }
]
)}
>
<View style={{ flex: 1, backgroundColor: 'white', paddingTop: 20 }}>
<Text style={styles.text}>
Laundry Service Provider Type
</Text>
<View style={{ height: 130, marginTop: 20 }}>
<ScrollView
horizontal={true}
showsHorizontalScrollIndicator={false}
>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PlaceOrder')} activeOpacity={0.7}><Category name="Dry Clean" /></TouchableOpacity>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PlaceOrder')} activeOpacity={0.7}><Category name="Iron"/></TouchableOpacity>
<TouchableOpacity onPress={()=> this.props.navigation.navigate('PlaceOrder')} activeOpacity={0.7}><Category name="Dry Clean + Iron" /></TouchableOpacity>
</ScrollView>
</View>
<View style={{ marginTop: 40}}>
<Text style={styles.text}>
Find Nearby LSP
</Text>
<Text style={{ fontWeight: '100', marginTop: 10,paddingHorizontal: 20 }}>
Verified LSP Providers
</Text>
<View style={{ marginTop: 20, paddingHorizontal: 15
}}>
<FlatList
data={data}
renderItem={({item})=>{
return renderList(item)
}}
keyExtractor={item=>item.id}
navigation={this.props.navigation}
/>
</View>
</View>
</View>
<View style={{ marginTop: 40 }}>
<Text style={styles.text}>
Express Mode
</Text>
<View style={{ paddingHorizontal: 20, marginTop: 20, flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between' }}>
<Expressmode width={width}
name="LSP1"
type="Dry Clean"
price={82}
rating={4}
/>
<Expressmode width={width}
name="LSP2"
type="Iron + Dry Clean"
price={82}
rating={4}
/>
<Expressmode width={width}
name="LSP3"
type="Iron"
price={82}
rating={4}
/>
</View>
</View>
</ScrollView>
</View>
</SafeAreaView>
);
;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center"
},
text: {
fontSize: 24,
fontWeight:'700',
paddingHorizontal: 20
}
});
'HomeScreen.js' contains another component where I had successfully used the navigation to navigate to 'PlaceorderScreen.js'. But when I call this navigation inside Flatlist it gives the error.
NearbyLSP.js
import React from "react";
import { View, Text, StyleSheet, TouchableOpacity, Dimensions, Image } from "react-native";
import { Card } from "react-native-paper" ;
const { width } = Dimensions.get('window')
export default class NearbyLSP extends React.Component {
render() {
return (
<View>
<Card style={styles.mycard}>
<View style={{ width: width - 40, height: 200}} >
<Image
style={{ flex: 1, height: null, width: null, resizeMode: 'cover', borderRadius: 5, borderWidth: 1, borderColor: '#dddddd' }}
source={require('../assets/a.jpeg')}
/>
<Text>{this.props.name}</Text>
</View>
</Card>
</View>
);
}
}
const styles = StyleSheet.create({
mycard: {
margin: 5
}
});
App.js
import React from "react";
import { createAppContainer, createSwitchNavigator , createBottomTabNavigator } from "react-navigation";
import { createStackNavigator } from "react-navigation-stack";
import LoadingScreen from "./screens/LoadingScreen";
import LoginScreen from "./screens/LoginScreen";
import SignupScreen from "./screens/SignupScreen";
import HomeScreen from "./screens/HomeScreen";
import AboutScreen from "./screens/AboutScreen";
import PastorderScreen from "./screens/PastorderScreen";
import TrackScreen from "./screens/TrackScreen";
import ProfileScreen from "./screens/ProfileScreen";
import PlaceorderScreen from "./screens/PlaceorderScreen";
import MapsScreen from "./screens/MapsScreen";
import NearbyLSP from "./screens/NearbyLSP";
import { Ionicons , MaterialIcons } from '#expo/vector-icons';
import * as firebase from "firebase";
const firebaseConfig = {
apiKey: "AIzaSyAhwjD3jodBg6JGJ7Oo72r7-m2T5wwPaUg",
authDomain: "a4project-2d896.firebaseapp.com",
databaseURL: "https://a4project-2d896.firebaseio.com",
projectId: "a4project-2d896",
storageBucket: "a4project-2d896.appspot.com",
messagingSenderId: "181932238433",
appId: "1:181932238433:web:aa3f6fa3947976a8352c20",
measurementId: "G-SW6N6N8JYK"
};
firebase.initializeApp(firebaseConfig);
const HomeStack = createStackNavigator({
Home: HomeScreen,
NearbyLSP:NearbyLSP,
PlaceOrder:PlaceorderScreen
},
{
defaultNavigationOptions: {
title:'Home',
headerStyle: {
backgroundColor:'#12B2C2',
},
headerTintColor:'#fff',
headerTitleStyle:{
fontWeight:'bold'
}
}
})
const OrderStack = createStackNavigator({
Order: TrackScreen,
Maps: MapsScreen,
},
{
defaultNavigationOptions: {
title:'Orders',
headerStyle: {
backgroundColor:'#12B2C2',
},
headerTintColor:'#fff',
headerTitleStyle:{
fontWeight:'bold'
}
}
})
const PastorderStack = createStackNavigator({
Pastorder: PastorderScreen,
},
{
defaultNavigationOptions: {
title:'Pastorder',
headerStyle: {
backgroundColor:'#12B2C2',
},
headerTintColor:'#fff',
headerTitleStyle:{
fontWeight:'bold'
}
}
})
const ProfileStack = createStackNavigator({
Profile: ProfileScreen,
About: AboutScreen
},
{
defaultNavigationOptions: {
title:'Profile',
headerStyle: {
backgroundColor:'#12B2C2',
},
headerTintColor:'#fff',
headerTitleStyle:{
fontWeight:'bold'
}
}
})
const AuthStack = createStackNavigator({
Login: LoginScreen,
Signup: SignupScreen
},
{
defaultNavigationOptions: {
headerStyle: {
backgroundColor:'#12B2C2',
},
headerTintColor:'#fff',
headerTitleStyle:{
fontWeight:'bold'
}
}
})
const myTabs= createBottomTabNavigator({
Home:HomeStack,
Orders:OrderStack,
Profile:ProfileStack,
Pastorder:PastorderStack
},
{
defaultNavigationOptions: ({ navigation })=> {
return {
tabBarIcon:({tintColor})=>{
const { routeName } = navigation.state;
let myicon
if(routeName=="Home"){
myicon='md-home'
return <Ionicons name={myicon} size={30} color={tintColor}/>
}else if(routeName=="Profile"){
myicon='md-person'
return <Ionicons name={myicon} size={30} color={tintColor}/>
}else if(routeName=="Orders"){
myicon='md-book'
return <Ionicons name={myicon} size={30} color={tintColor}/>
}else if(routeName=="Pastorder"){
myicon='library-books'
return <MaterialIcons name={myicon} size={30} color={tintColor}/>
}
}
};
}
});
export default createAppContainer(
createSwitchNavigator(
{
Loading: LoadingScreen,
Auth: AuthStack,
App: myTabs
},
{
initialRouteName: "Loading"
},
)
);
Just writing navigation={this.props.navigation} in Flatlist won't let you navigate to the desired screen. You have to create a Touchable component in the Flatlist and add the navigation logic into the onPress logic of this Touchable Component.
this.props.navigation is a collection of data and methods, if you need to navigate through screens you need to use this.props.navigation.navigate('PlaceOrder')} instead, this is the method that does the navigation for you. You can console.log(this.props.navigation) to understand better.
Refer to how navigation is implemented in this answer https://stackoverflow.com/a/45407626/8851276
The code within FlatList of 'HomeScreen.js' is modified as follows
<FlatList
data={data}
renderItem={this.rendeList}
keyExtractor={item=>item.id}
/>
and the renderList function which was outside the class component is transferred inside and modified as
renderList = ({ item }) => {
return (
<TouchableOpacity
onPress={()=> this.props.navigation.navigate('PlaceOrder')}
activeOpacity={0.7}>
<NearbyLSP name={item.name}/>
</TouchableOpacity>
);
};
Due to transferring the renderList function inside the class component, it gets access to the this.props and it can be used for navigation to new screen.
I am building a searchBar, whenever I do search I get undefined error because the value doesn't exist in state till I finish the whole value so I know that I will get error yet I am unable to solve it so I am trying to render cards according to the search input I think I did hard code my homeScreen I am not sure if I am doing it even right and here it comes the question to the three if statements inside render that I have is it good practice ? is it professional ? can i do something else which makes code easier to read and shorter ? I was thinking of eliminating the third if but I wasn't able to change state inside the second if so I had to add the toggle search function to let it work any ideas on how to eliminate the third if would be nice ..! thank you in advance guys
homeScreen.js
import axios from 'axios';
import React from 'react';
import {
ActivityIndicator,
ScrollView,
Text,
View,
TouchableOpacity,
TextInput,
} from 'react-native';
import Card from '../Components/Card/card';
export default class HomeScreen extends React.Component {
state = {
shows: [],
isLoading: true,
search: false,
title: '',
};
componentDidMount() {
this.getData();
}
toggleSearch = () => {
console.log('hlelleloe');
this.setState({
search: true,
});
};
getData = () => {
const requestUrls = Array.from({length: 9}).map(
(_, idx) => `http://api.tvmaze.com/shows/${idx + 1}`,
);
const handleResponse = data => {
this.setState({
isLoading: false,
shows: data,
});
};
const handleError = error => {
console.log(error);
this.setState({
isLoading: false,
});
};
Promise.all(requestUrls.map(url => axios.get(url)))
.then(handleResponse)
.catch(handleError);
};
render() {
const {isLoading, shows, search, title} = this.state;
if (isLoading) {
return <ActivityIndicator size="large" color="#0000ff" />;
} else if (!search) {
return (
<View>
<View>
<TouchableOpacity
onPress={this.toggleSearch}
style={{height: 300, width: 300}}>
<Text style={{textAlign: 'center', fontSize: 40}}>
Press to Search
</Text>
</TouchableOpacity>
</View>
<ScrollView style={{backgroundColor: '#E1E8E7'}}>
{shows.length &&
shows.map((show, index) => {
return (
<Card
key={show.data.id}
title={show.data.name}
rating={show.data.rating.average}
source={show.data.image.medium}
genres={show.data.genres}
language={show.data.language}
network={show.data.network}
schedule={show.data.schedule}
summary={show.data.summary}
navigation={this.props.navigation}
/>
);
})}
</ScrollView>
</View>
);
} else if (search) {
console.log(title);
return (
<View>
<TextInput
style={{
height: 100,
width: 100,
borderColor: 'gray',
borderWidth: 1,
}}
onChangeText={searchedTitle => (
<Card title={shows.data.searchedTitle} />
)}
/>
</View>
);
}
}
}
Card.js
import React from 'react';
import {
Image,
View,
Text,
Button,
StyleSheet,
TouchableOpacity,
} from 'react-native';
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from 'react-native-responsive-screen';
import Icon from 'react-native-vector-icons/FontAwesome';
const Card = props => {
return (
<View style={styles.container}>
<Image style={styles.Image} source={{uri: `${props.source}`}} />
<Text style={styles.title}>{props.title}</Text>
<View style={styles.ratingContainer}>
<Text style={styles.rating}>Rating: {props.rating}</Text>
<Icon name="star" size={30} color="grey" />
</View>
<TouchableOpacity
style={styles.button}
onPress={() => {
props.navigation.navigate('Details', {
title: props.title,
rating: props.rating,
source: props.source,
genres: props.genres,
language: props.language,
network: props.network,
schedule: props.schedule,
summary: props.summary,
});
}}>
<Text style={styles.buttonText}>Press for details </Text>
</TouchableOpacity>
</View>
);
};
export default Card;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
},
Image: {
flex: -1,
width: wp('90%'),
height: hp('65%'),
},
title: {
flex: 1,
fontSize: 40,
borderRadius: 10,
color: '#3C948B',
margin: 15,
justifyContent: 'center',
alignItems: 'center',
},
ratingContainer: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: 'white',
elevation: 6,
justifyContent: 'space-between',
borderWidth: 1,
width: 300,
},
rating: {
fontSize: 25,
paddingLeft: 15,
},
button: {
flex: 1,
color: '#3C948B',
backgroundColor: '#3C948B',
height: hp('7%'),
width: wp('70%'),
margin: 20,
alignItems: 'center',
borderBottomLeftRadius: 10,
borderTopRightRadius: 10,
},
buttonText: {
flex: 1,
fontSize: 25,
},
});
you Need to implement a constructor for your React component.
Typically, in React constructors are only used for two purposes:
Initializing local state by assigning an object to this.state
Binding event handler methods to an instance
Do
state = {
shows: [],
isLoading: true,
search: false,
title: '',
};
replace this with
constructor(props){
super(props);
this.state = {
shows: [],
isLoading: true,
search: false,
title: '',
};
}
I've been trying to build an application which will goto login screen after splash. Once the user logs in, it should be directed to a screen which has drawer navigation and tabs in it. I've been trying to implement this using react native expo. It's working fine in expo. But once I generate an APK and try to use it, after logging in it redirects to splash and login without showing any content. I've been using react-navigation package for navigating between the screens
My Navigator.js:
import React from 'react';
import { createAppContainer, createDrawerNavigator, createStackNavigator } from 'react-navigation';
import SplashScreen from '../screens/SplashScreen';
import Screen1 from '../screens/Screen1';
import Screen2 from '../screens/Screen2';
import Screen3 from '../screens/Screen3';
import MainDrawer from '../common/MainDrawer';
const LoginNavigator = createStackNavigator({
splash: SplashScreen
}, {
headerMode: 'none',
navigationOptions: {
headerVisibile: false,
}
});
const DrawerNavigator = createDrawerNavigator({
screen1: Screen1,
screen2: Screen2,
screen3: Screen3,
}, {
initialRouteName: 'screen1',
contentComponent: props => <MainDrawer {...props} />,
drawerWidth: 350,
headerMode: 'none',
navigationOptions: {
headerVisible: false,
}
});
const TotalNavigator = createStackNavigator({
loginStack: { screen: LoginNavigator },
drawerStack: { screen: DrawerNavigator },
}, {
headerMode: 'none',
initialRouteName: 'loginStack',
navigationOptions: {
headerVisible: false,
}
})
PrimaryNavigator = createAppContainer(TotalNavigator);
export default PrimaryNavigator;
My MainDrawer.js:
import React from 'react';
import { View, Text } from 'react-native';
import Image from 'react-native-remote-svg';
export default class MainDrawer extends React.Component {
constructor(props) {
super(props);
}
static navigationOptions = {
header: null,
};
render() {
return (
<View style={{ width: '100%', height: '100%', backgroundColor: '#2C2663' }}>
<View style={{ left: '7%', top: '10%' }}>
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
<Image source={require('../assets/images/user_pic.svg')} />
<Text style={{ color: '#fff', fontSize: 25, flexDirection: 'row', left: '-28%', top: '10%' }}> SomeOne</Text>
</View>
<View style={{ width: '80%', borderBottomWidth: 1, borderBottomColor: '#C0C0C0', top: '20%' }} />
<Text style={{ color: '#C0C0C0', fontSize: 11, top: '30%' }}>
{`Some dummy text`}</Text>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', top: '40%' }}>
<Image style={{ width: 30, height: 30 }} source={require('../assets/images/icon.svg')} />
<Text style={{ color: '#fff', fontSize: 20, flexDirection: 'row', left: '-40%', top: '10%' }}
onPress={() => this.props.navigation.navigate('screen1')}> Screen 1 </Text>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', top: '50%' }}>
<Image style={{ width: 30, height: 30 }} source={require('../assets/images/icon2.svg')} />
<Text style={{ color: '#fff', fontSize: 20, flexDirection: 'row', left: '-42%', top: '10%' }}
onPress={() => this.props.navigation.navigate('screen2')}
> Screen 2</Text>
</View>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', top: '60%' }}>
<Image style={{ width: 30, height: 30 }} source={require('../assets/images/icon3.svg')} />
<Text style={{ color: '#fff', fontSize: 20, flexDirection: 'row', left: '-16%', top: '10%' }}
onPress={() => this.props.navigation.navigate('screen3')}
> Screen 3</Text>
</View>
</View>
</View>);
}
}
My SplashScreen.js:
import React from 'react';
import { Animated } from 'react-native';
import LottieView from 'lottie-react-native';
import LoginScreen from './LoginScreen.js';
export default class SplashScreen extends React.Component {
constructor(props) {
super(props);
this.state = { isAnimationVisible: true, animationProgress: new Animated.Value(0) };
this.homeScreen = this.homeScreen.bind(this);
}
static navigationOptions = {
header: null,
};
componentDidMount() {
Animated.timing(this.state.animationProgress, { toValue: 1, duration: 15000 })
.start(() => this.setState(s => ({ ...s, isAnimationVisible: false })));
}
//Navigate to Home screen
homeScreen() {
this.props.navigation.navigate('drawerStack');
}
render() {
if (this.state.isAnimationVisible) {
const interpolation = this.state.animationProgress.interpolate({ inputRange: [0, 1], outputRange: [0, 1] });
return (
<LottieView
source={require('../assets/animations/splash.json')}
progress={interpolation}
autoPlay
loop={false}
resizeMode='cover'
/>
);
}
else {
return (<LoginScreen goToHome={this.homeScreen} />);
}
}
}
My LoginScreen.js:
import React from 'react';
import { View, Image, Text, TextInput, KeyboardAvoidingView, ActivityIndicator } from 'react-native';
import { Button } from 'native-base';
import loginStyles from '../styles/loginStyles';
class LoginScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
};
this.onButtonPress = this.onButtonPress.bind(this);
}
static navigationOptions = {
header: null,
};
onButtonPress() {
let Users = list of users;
for (let i = 0; i < Users.length; i++) {
if ((Users[i].username == this.state.email) && (Users[i].password = this.state.password)) {
this.props.goToHome();
}
}
render() {
// On pressing login after giving credentials this.onButtonPress() is called
}
}
export default LoginScreen;
Can someone pointout where the issue is and suggest a fix? Thanks in advance.
Instead of creating TotalNavigator as StackNavigator use SwitchNavigation instead at the root, like this:
SwitchNavigator
|
|-SplashScreen # Create this as single screen no need to create Stack, initial screen
|
|-LoginNavigator
|
|-DrawerNavigator
Then in the LoginScreen just navigate to MainDrawer directly, it will handle the back press as well.
I Have navigation system of createMaterialTopTabNavigator and createDrawerNavigator I try to get a menu bar icon in the top left side of the createMaterialTopTabNavigator but till this moment I can't figure out how to add this element at the particular place , is there any react native property that may correspond to that situation , could you please help
import React, { Component } from "react";
import {.. } from "react-native";
import Icon from 'react-native-vector-icons/MaterialIcons'
import { createSwitchNavigator, createDrawerNavigator ,DrawerItems,createMaterialTopTabNavigator,createStackNavigator} from 'react-navigation'
import screens ...
console.disableYellowBox = true;
const TabBarNavig = createMaterialTopTabNavigator({
Places : {
screen :Players,
navigationOptions: ({ navigation }) => ({
title: 'Placements'
}
)
},
GetPlaces : Teams,
New : Matchs
},
{
tabBarOptions: {
scrollEnabled: true,
labelStyle: {
fontSize: 10,
paddingTop:10
},
tabStyle: {
width: Dimensions.get('window').width / 3,
},
style: {
backgroundColor: '#38A1F3',
height: 80
},
indicatorStyle: {
backgroundColor: '#fff',
},
activeTintColor : 'white',
inactiveTintColor : '#ddd',
showIcon : true,
showLabel: true
}
}
);
const DrawerContent = (props) => (
<ScrollView contentContainerStyle={{flexGrow: 1 }}>
<View
style={{
paddingTop: 35,
paddingBottom : 35,
backgroundColor: '#38A1F3',
alignItems: 'center',
justifyContent: 'center',
color: '#FFF'
}}
>
<Image
source={require('./assets/logo.png')}
style={{width:110,height:110 , marginBottom: 10,borderColor:'#FFF',borderWidth:0}}
/>
</View>
<View style={{ backgroundColor: '#FFF',alignItems: 'flex-start',justifyContent: 'center',marginTop:40,marginLeft:20}}>
<DrawerItems {...props}
getLabel = {(scene) => (
<View style={styles.button}>
<Image source={arry[props.getLabel(scene)]} style={{marginRight:20,width:24,height:24}} />
<Text style={styles.buttonText}>{props.getLabel(scene)}</Text>
</View>
)}
/>
</View>
</ScrollView>
)
const arry = {Home:require('./assets/home.png'),Days:require('./assets/icon.png')};
const AppDrawerNavigator = createDrawerNavigator({
Home: TabBarNavig,
Days: Dating
},
{
contentComponent: DrawerContent,
}
)
const Routes = createSwitchNavigator({
App: AppDrawerNavigator
})
export default Routes;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
buttonText:{
color:'#000',
fontStyle: 'italic',
fontSize: 16,
},
button:{
flexDirection: 'row',
paddingBottom : 20
}
});
As my knowledge, in createBottomTopNavigator according to docs there is no option to add menu left or right docs
you can set left icon through navigationOptions of your component like this
static navigationOptions = ({navigation}) => ({
headerLeft: <Icon name='....' ....../>,
headerRight: <Icon name='....' ....../>
})