this.props.navigation.navigate() is not working for AppDrawerNavigator - react-native

I'm facing issue in navigation in android app. When button is clicked app screen freezes, it does not redirect to next screen which is createDrawerNavigator() screen. Calling it from the Country selection screen.
import React, { Component } from "react";
import { View, Image, StyleSheet } from "react-native";
import AsyncStorage from "#react-native-community/async-storage";
import {
createSwitchNavigator,
createStackNavigator,
createDrawerNavigator,
createAppContainer
} from "react-navigation";
import CustomizedStatusBar from "./src/components/CustomizedStatusBar";
import Splash from "./src/screens/Splash";
import Login from "./src/screens/Login";
import CountrySelection from "./src/screens/CountrySelection";
import Dashboard from "./src/screens/Dashboard";
import ImportantNotice from "./src/screens/ImportantNotice";
import ApplicationForm from "./src/screens/ApplicationForm";
import ApplicationForm2 from "./src/screens/ApplicationForm2";
import ApplicationForm3 from "./src/screens/ApplicationForm3";
import ApplicationForm4 from "./src/screens/ApplicationForm4";
import Instructions from "./src/screens/Instructions";
import TravelHistory from "./src/screens/TravelHistory";
import TravelHistoryDetails from "./src/screens/TravelHistoryDetails";
import DownloadStamp from "./src/screens/DownloadStamp";
import LearnAbout from "./src/screens/LearnAbout";
import Advices from "./src/screens/Advices";
import TellAFriend from "./src/screens/TellAFriend";
import Contact from "./src/screens/Contact";
import SideMenu from "./src/screens/SideMenu";
import SignatureCapture from "./src/screens/SignatureCapture";
import CMS from "./src/screens/CMS";
import GLOBAL from "./src/config/constants";
import { Provider } from "react-redux";
import store from "./src/redux/store/index";
import NavigationDrawerStructure from "./src/components/NavigationDrawerStructure";
import NavigationService from "./src/config/NavigationService";
const CMSStackNavigator = createStackNavigator({
CMS: {
screen: CMS
}
});
const HomeStackNavigator = createStackNavigator({
Home: {
screen: Dashboard
}
});
const ApplicationFormStackNavigator = createStackNavigator({
ApplicationForm: {
screen: ApplicationForm,
navigationOptions: ({ navigation }) => ({
title: "",
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
},
headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
})
}
});
const ApplicationForm2StackNavigator = createStackNavigator({
ApplicationForm2: {
screen: ApplicationForm2,
navigationOptions: ({ navigation }) => ({
title: "",
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
},
headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
})
}
});
const ApplicationForm3StackNavigator = createStackNavigator({
ApplicationForm3: {
screen: ApplicationForm3,
navigationOptions: ({ navigation }) => ({
title: "",
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
},
headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
})
}
});
const SignatureCaptureStackNavigator = createStackNavigator({
SignatureCapture: {
screen: SignatureCapture,
navigationOptions: ({ navigation }) => ({
title: "",
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
},
headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
})
}
});
const ApplicationForm4StackNavigator = createStackNavigator({
ApplicationForm4: {
screen: ApplicationForm4,
navigationOptions: ({ navigation }) => ({
title: "",
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
},
headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
})
}
});
const TravelHistoryStackNavigator = createStackNavigator({
TravelHistory: {
screen: TravelHistory
}
});
const TravelHistoryDetailsStackNavigator = createStackNavigator({
TravelHistoryDetails: {
screen: TravelHistoryDetails
}
});
const DownloadStampStackNavigator = createStackNavigator({
DownloadStamp: {
screen: DownloadStamp,
navigationOptions: ({ navigation }) => ({
title: "IMMIGRATION STAMP",
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
},
headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
})
}
});
const TellAFriendStackNavigator = createStackNavigator({
TellAfriend: {
screen: TellAFriend,
navigationOptions: ({ navigation }) => ({
title: "TELL A FRIEND",
headerLeft: <NavigationDrawerStructure navigationProps={navigation} />,
headerStyle: {
backgroundColor: GLOBAL.COLOR.PRIMARY_COLOR
},
headerTintColor: GLOBAL.COLOR.HEADER_TINT_COLOR
})
}
});
const AppDrawerNavigator = createDrawerNavigator(
{
home: {
screen: HomeStackNavigator
},
application_form: {
screen: ApplicationFormStackNavigator,
navigationOptions: {
drawerLabel: "",
drawerIcon: ({ tintColot }) => (
<Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
)
}
},
application_form2: {
screen: ApplicationForm2StackNavigator,
navigationOptions: {
drawerLabel: "",
drawerIcon: ({ tintColot }) => (
<Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
)
}
},
application_form3: {
screen: ApplicationForm3StackNavigator,
navigationOptions: {
drawerLabel: "",
drawerIcon: ({ tintColot }) => (
<Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
)
}
},
signature_capture: {
screen: SignatureCaptureStackNavigator,
navigationOptions: {
drawerLabel: "",
drawerIcon: ({ tintColot }) => (
<Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
)
}
},
application_form4: {
screen: ApplicationForm4StackNavigator,
navigationOptions: {
drawerLabel: "",
drawerIcon: ({ tintColot }) => (
<Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
)
}
},
travel_history: {
screen: TravelHistoryStackNavigator
},
travel_history_details: { screen: TravelHistoryDetailsStackNavigator },
download_stamp: {
screen: DownloadStampStackNavigator,
navigationOptions: {
drawerLabel: "IMMIGRATION STAMP",
drawerIcon: ({ tintColot }) => (
<Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
)
}
},
tellafriend: {
screen: TellAFriendStackNavigator,
navigationOptions: {
drawerLabel: "TELL A FRIEND",
drawerIcon: ({ tintColot }) => (
<Image source={GLOBAL.MENU_ICON} style={{ width: 20, height: 20 }} />
)
}
},
cms: {
screen: CMSStackNavigator
}
},
{
contentComponent: SideMenu
}
);
export default class App extends Component {
constructor(props) {
super(props);
}
componentWillMount() {}
componentDidMount() {}
getPreferenceInfo = async () => {
const isLoggedIn = await AsyncStorage.getItem(
GLOBAL.PREFERENCE_STORAGE_KEY.IS_LOGGED_IN
);
const isLanguageSelected = await AsyncStorage.getItem(
GLOBAL.PREFERENCE_STORAGE_KEY.IS_LANGUAGE_SELECTED
);
return { isLoggedIn: isLoggedIn, isLanguageSelected: isLanguageSelected };
};
render() {
const AppSwitchNavigator = createSwitchNavigator(
{
SplashScreen: { screen: Splash },
LoginScreen: { screen: Login },
CountryScreen: { screen: CountrySelection },
DashboardScreen: { screen: AppDrawerNavigator }
},
{
initialRouteName: "AppScreen"
}
);
const AppContainer = createAppContainer(AppSwitchNavigator);
return (
<Provider store={store}>
<View style={{ flex: 1 }}>
<CustomizedStatusBar />
<AppContainer />
</View>
</Provider>
);
}
}
const styles = StyleSheet.create({
bg: {
width: "100%",
height: "100%"
}
});
// Calling it from CountrySelection.js (CountryScreen)
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
Image,
Keyboard,
TouchableWithoutFeedback,
TouchableOpacity,
SafeAreaView,
KeyboardAvoidingView,
ActivityIndicator,
Alert
} from "react-native";
import AsyncStorage from "#react-native-community/async-storage";
import { StackActions, NavigationActions } from "react-navigation";
import CustomInputBox from "../components/CustomInputBox";
import GLOBAL from "../config/constants";
import { connect } from "react-redux";
import {
selectCountryWithIndex,
openCountrySelectionView,
getCountries,
openLanguageSelectionView
} from "../redux/actions/index";
import CountrySelectionPicker from "../components/CountrySelectionPicker";
import LanguageSelectionPicker from "../components/LanguageSelectionPicker";
class CountrySelection extends Component {
constructor(props) {
super(props);
this.didPressSubmit = this.didPressSubmit.bind(this);
this.navigateAfterFinish = this.navigateAfterFinish.bind(this);
this.state = {
isLoading: true,
animating: false,
selectedCountry: null,
stores: []
};
}
static navigationOptions = {
header: null
};
navigateAfterFinish = screen => {
const resetAction = StackActions.reset({
actions: [NavigationActions.navigate({ routeName: "DashboardScreen" })]
});
this.props.navigation.dispatch(resetAction);
};
getSelectedCountryInfo = async () => {
try {
let value = await AsyncStorage.getItem(
GLOBAL.PREFERENCE_STORAGE_KEY.SELECTED_COUNTRY
);
let selectedIndex = await AsyncStorage.getItem(
GLOBAL.PREFERENCE_STORAGE_KEY.SELECTED_COUNTRY_INDEX
);
return { selectedCountry: value, selectedIndex: selectedIndex };
} catch (e) {
console.log(e);
}
};
onSelectLanguage = async (langCode, langId) => {
// Alert.alert(
// "Error",
// langCode + "==" + langId,
// [
// {
// text: "OK"
// }
// ],
// { cancelable: false }
// );
try {
await AsyncStorage.setItem(
GLOBAL.PREFERENCE_STORAGE_KEY.SELECTED_COUNTRY,
JSON.stringify(this.props.countrySelectionReducers.selectedCountry)
);
await AsyncStorage.setItem(
GLOBAL.PREFERENCE_STORAGE_KEY.SELECTED_COUNTRY_LANGUAGE_CODE,
langCode
);
await AsyncStorage.setItem(
GLOBAL.PREFERENCE_STORAGE_KEY.SELECTED_COUNTRY_LANGUAGE_CODE_ID,
langId
);
await AsyncStorage.setItem(
GLOBAL.PREFERENCE_STORAGE_KEY.IS_LANGUAGE_SELECTED,
"true"
);
return true;
} catch (e) {
// Alert.alert(
// "Error",
// e,
// [
// {
// text: "OK"
// }
// ],
// { cancelable: false }
// );
console.log(e);
return false;
}
};
getAllDatas = () => {
AsyncStorage.getAllKeys((err, keys) => {
AsyncStorage.multiGet(keys, (err, stores) => {
this.setState({ stores });
});
});
};
didPressSubmit = () => {
this.props.navigation.navigate("DashboardScreen");
};
componentWillMount() {}
componentDidMount() {
this.props.getCountries();
this.getAllDatas();
// this.getSelectedCountryInfo().then(data => {
// this.props.selectCountryWithIndex(
// JSON.parse(data.selectedCountry),
// parseInt(data.selectedIndex)
// );
// });
}
render() {
const { navigate } = this.props.navigation;
return (
<KeyboardAvoidingView behavior={"padding"} style={{ flex: 1 }}>
<View style={{ flex: 1 }}>
<SafeAreaView style={{ flex: 1 }}>
<TouchableWithoutFeedback
onPress={Keyboard.dismiss}
accessible={false}
>
<View style={styles.container}>
<Image style={styles.bg} source={GLOBAL.LOGIN_BGIMG} />
<View style={styles.formContainer}>
<Text style={styles.textContainer}>
{GLOBAL.SELECT_COUNTRY}
</Text>
<View style={{ flex: 1 }}>
<CustomInputBox
icon={
this.props.countrySelectionReducers.selectedCountry !==
null
? {
uri: this.props.countrySelectionReducers
.selectedCountry.country_logo
}
: null
}
leftInputIconStyle={
this.props.countrySelectionReducers.selectedCountry !==
null
? {
width: 32,
height: 20,
borderWidth: 0.5,
borderColor: "#c6c6c6"
}
: null
}
keyboardType="default"
returnKeyType="next"
showPlaceholder={false}
_placeholder={GLOBAL.COUNTRY_PLACEHOLDER}
showRightIcon={true}
rightIcon={GLOBAL.COUNTRY_RIGHT_ICON}
defaultValue={
this.props.countrySelectionReducers.selectedCountry !==
null
? this.props.countrySelectionReducers.selectedCountry
.country_name
: null
}
/>
<TouchableOpacity
style={{
backgroundColor: "transparent",
top: 0,
bottom: 0,
left: 0,
right: 0,
position: "absolute"
}}
onPress={() => this.props.openCountrySelectionView()}
/>
</View>
<View style={{ flex: 1 }}>
<CustomInputBox
icon={
this.props.countrySelectionReducers.selectedLanguage !==
null
? {
uri:
GLOBAL.URL.uploads +
this.props.countrySelectionReducers
.selectedLanguage.language_code +
".png"
}
: null
}
leftInputIconStyle={
this.props.countrySelectionReducers.selectedLanguage !==
null
? {
width: 32,
height: 20,
borderWidth: 0,
borderColor: "#c6c6c6"
}
: null
}
keyboardType="default"
returnKeyType="done"
showPlaceholder={false}
_placeholder={GLOBAL.LANGUAGE_PLACEHOLDER}
showRightIcon={true}
rightIcon={GLOBAL.COUNTRY_RIGHT_ICON}
customStyle={{ marginTop: 20 }}
defaultValue={
this.props.countrySelectionReducers.selectedLanguage !==
null
? this.props.countrySelectionReducers.selectedLanguage
.language_name
: null
}
/>
<TouchableOpacity
style={{
backgroundColor: "transparent",
top: 0,
bottom: 0,
left: 0,
right: 0,
position: "absolute"
}}
onPress={() => this.props.openLanguageSelectionView()}
/>
</View>
<TouchableOpacity
style={[styles.btn, { marginTop: 30 }]}
onPress={() => this.didPressSubmit()}
>
<Image
style={styles.btnImg}
resizeMode="contain"
source={GLOBAL.BTN_BGIMG}
/>
<View style={styles.btnContainer}>
<Text style={styles.btnText}>{GLOBAL.LOGINBTN}</Text>
</View>
</TouchableOpacity>
</View>
{this.props.countrySelectionReducers.isAnimating ? (
<View
style={{
width: "100%",
height: "100%",
position: "absolute",
justifyContent: "center",
alignItems: "center"
}}
>
<View
style={{
flex: 1,
backgroundColor: "#000000",
width: "100%",
height: "100%"
}}
opacity={0.6}
/>
<ActivityIndicator
style={{ alignSelf: "center", position: "absolute" }}
size="large"
color="#ffffff"
/>
</View>
) : null}
</View>
</TouchableWithoutFeedback>
<CountrySelectionPicker />
<LanguageSelectionPicker />
</SafeAreaView>
</View>
</KeyboardAvoidingView>
);
}
}
const mapStateToProps = state => {
return {
countrySelectionReducers: state.CountrySelectionReducers
};
};
export default connect(
mapStateToProps,
{
selectCountryWithIndex,
openCountrySelectionView,
getCountries,
openLanguageSelectionView
}
)(CountrySelection);
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center"
},
bg: {
width: "100%",
height: "100%"
},
formContainer: {
position: "absolute",
width: "100%",
paddingHorizontal: 30,
flexGrow: 1
},
textContainer: {
fontSize: 20,
fontWeight: "bold",
color: "#ffffff",
alignSelf: "center",
textAlign: "center",
marginBottom: 30
},
btn: {
alignItems: "center",
justifyContent: "center"
},
btnText: {
fontSize: 20,
fontWeight: "bold",
color: "#ffffff",
alignSelf: "center"
},
btnContainer: {
alignItems: "center",
justifyContent: "center",
position: "absolute"
},
btnImg: {
resizeMode: "contain",
left: 0,
right: 0,
top: 0,
bottom: 0,
height: 46
}
});
Wanted to redirect user to DashboardScreen from CountryScreen using this.props.navigation.navigate("DashboardScreen"). But it fails. No error is thrown.

This has been resolved. The issue was with hybrid-crypto-js library. It was throwing an exception due to which navigation stops.

Related

React Native -- Even after imports and exports are correct getting error "The component for route 'Menu' must be a react component"

I have encountered the mentioned error. I searched for this through different links as. I changed import and export according to the answer to this question but the same error is still there. I have done imports and exports correctly.*
This is
MainComponent.js file where the Menu component is imported.
import React, { Component } from 'react';
import Menu from './MenuComponent';
import Dishdetail from './DishDetailComponent';
import Contact from './ContactComponent';
import About from './AboutComponent';
import Home from './HomeComponent';
import { View, Platform, Image, StyleSheet, ScrollView, Text } from 'react-native';
import { createStackNavigator, createDrawerNavigator, DrawerItems, SafeAreaView, SrollView } from 'react-navigation';
import { Icon } from 'react-native-elements';
import { connect } from 'react-redux';
import { fetchDishes, fetchComments, fetchPromos, fetchLeaders } from '../redux/ActionCreators';
const mapStateToProps = (state) => {
return {
dishes: state.dishes,
promotions: state.promotions,
leaders: state.leaders,
};
};
const mapDispatchToProps = (dispatch) => ({
fetchDishes: () => dispatch(fetchDishes()),
fetchComments: () => dispatch(fetchComments()),
fetchPromos: () => dispatch(fetchPromos()),
fetchLeaders: () => dispatch(fetchLeaders()),
});
const MenuNavigator = createStackNavigator(
{
Menu: {
screen: Menu,
navigationOptions: ({ navigation }) => ({
headerLeft: <Icon name="menu" size={24} color="#fff" onPress={() => navigation.toggleDrawer()} />,
}),
},
Dishdetail: { screen: Dishdetail },
},
{
initialRouteName: 'Menu',
navigationOptions: {
headerStyle: {
backgroundColor: '#512DA8',
},
headerTintColor: '#fff',
headerTitleStyle: {
color: '#fff',
},
},
}
);
const HomeNavigator = createStackNavigator(
{
Home: { screen: Home },
},
{
navigationOptions: ({ navigation }) => ({
headerStyle: {
backgroundColor: '#512DA8',
},
headerTintColor: '#fff',
headerTitleStyle: {
color: '#fff',
},
headerLeft: <Icon name="menu" size={24} color="#fff" onPress={() => navigation.toggleDrawer()} />,
}),
}
);
const ContactNavigator = createStackNavigator(
{
Contact: { screen: Contact },
},
{
navigationOptions: ({ navigation }) => ({
headerStyle: {
backgroundColor: '#512DA8',
},
headerTintColor: '#fff',
headerTitleStyle: {
color: '#fff',
},
headerLeft: <Icon name="menu" size={24} color="#fff" onPress={() => navigation.toggleDrawer()} />,
}),
}
);
const AboutNavigator = createStackNavigator(
{
About: { screen: About },
},
{
navigationOptions: ({ navigation }) => ({
headerStyle: {
backgroundColor: '#512DA8',
},
headerTintColor: '#fff',
headerTitleStyle: {
color: '#fff',
},
headerLeft: <Icon name="menu" size={24} color="#fff" onPress={() => navigation.toggleDrawer()} />,
}),
}
);
const CustomDrawerContentComponent = (props) => (
<ScrollView>
<SafeAreaView style={styles.container} forceInset={{ top: 'always', horizontal: 'never' }}>
<View style={styles.drawerHeader}>
<View style={{ flex: 1 }}>
<Image source={require('./images/logo.png')} style={styles.drawerImage} />
</View>
<View style={{ flex: 2 }}>
<Text style={styles.drawerHeaderText}>VangooApp</Text>
</View>
</View>
<DrawerItems {...props} />
</SafeAreaView>
</ScrollView>
);
const MainNavigator = createDrawerNavigator(
{
Home: {
screen: HomeNavigator,
navigationOptions: {
title: 'Home',
drawerLabel: 'Home',
drawerIcon: ({ tintColor }) => <Icon name="home" type="font-awesome" size={24} color={tintColor} />,
},
},
About: {
screen: AboutNavigator,
navigationOptions: {
title: 'About',
drawerLabel: 'About Us',
drawerIcon: ({ tintColor }) => (
<Icon name="info-circle" type="font-awesome" size={24} color={tintColor} />
),
},
},
Menu: {
screen: MenuNavigator,
navigationOptions: {
title: 'Menu',
drawerLabel: 'Menu',
drawerIcon: ({ tintColor }) => <Icon name="list" type="font-awesome" size={24} color={tintColor} />,
},
},
Contact: {
screen: ContactNavigator,
navigationOptions: {
title: 'Contact',
drawerLabel: 'Contact Us',
drawerIcon: ({ tintColor }) => (
<Icon name="address-card" type="font-awesome" size={22} color={tintColor} />
),
},
},
},
{
drawerBackgroundColor: '#D1C4E9',
contentComponent: CustomDrawerContentComponent,
}
);
class MainComponent extends Component {
componentDidMount() {
this.props.fetchDishes();
this.props.fetchComments();
this.props.fetchPromos();
this.props.fetchLeaders();
}
render() {
return (
<View style={{ flex: 1, paddingTop: Platform.OS === 'ios' ? 0 : Expo.Constants.statusBarHeight }}>
<MainNavigator />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
drawerHeader: {
backgroundColor: '#512DA8',
height: 140,
alignItems: 'center',
justifyContent: 'center',
flex: 1,
flexDirection: 'row',
},
drawerHeaderText: {
color: '#fff',
fontSize: 24,
fontWeight: 'bold',
},
drawerImage: {
margin: 10,
width: 80,
height: 60,
},
});
export default connect(mapStateToProps, mapDispatchToProps)(MainComponent);
MenuComponent.js
import React, { Component } from 'react';
import { FlatList } from 'react-native';
import { Tile } from 'react-native-elements';
import { connect } from 'react-redux';
import { baseUrl } from '../shared/baseURL';
const mapStateToProps = (state) => {
return {
dishes: state.dishes,
};
};
class Menu extends Component {
static navigationOptions = {
title: 'Menu',
};
render() {
const renderMenuItem = ({ item, index }) => {
return (
<Tile
key={index}
title={item.name}
caption={item.description}
featured
onPress={() => navigate('Dishdetail', { dishId: item.id })}
imageSrc={{ uri: baseUrl + item.image }}
/>
);
};
const { navigate } = this.props.navigation;
return (
<FlatList
data={this.props.dishes.dishes}
renderItem={renderMenuItem}
keyExtractor={(item) => item.id.toString()}
/>
);
}
}
export default connect(mapStateToProps)(Menu);
[![Error][1]][1]

How do I solve this: 'TypeError: undefined is not an object (evaluating '_this.props.navigationProps.toggleDrawer')'

A few days into React-Native, I am trying to implement a navigation drawer in my app.
However, I am not able to solve the error TypeError: undefined is not an object (evaluating '_this.props.navigationProps.toggleDrawer') when I tap the TouchableOpacity component that should trigger the drawer.
Following is the code I have used:
Header.js
import React, { Component } from 'react';
import { View, StyleSheet, Image, TouchableOpacity, Platform } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createDrawerNavigator } from 'react-navigation-drawer';
import { createStackNavigator } from 'react-navigation-stack';
import Screen1 from '../pages/screen1';
import Screen2 from '../pages/screen2';
import Screen3 from '../pages/screen3';
import logo from '../assets/logo.png';
import profileView from '../assets/profileIcon.png';
import menuDots from '../assets/3DotsMenu.png';
import { StatusBarHeight } from '../components/StatusBarHeight';
const statusBarHeight = StatusBarHeight
class Header extends Component {
toggleDrawer = () => {
this.props.navigationProps.toggleDrawer();
};
render() {
return (
<View>
<CreateDrawer />
<View style={styles.header} />
<View style={styles.headerContainer}>
<View style={styles.imageHolder}>
<TouchableOpacity
activeOpacity={0.6}
onPress={this.toggleDrawer.bind(this)}
>
<View>
<Image style={styles.menu} source={menuDots} />
</View>
</TouchableOpacity>
<TouchableOpacity activeOpacity={0.6}>
<View>
<Image style={styles.logo} source={logo} />
</View>
</TouchableOpacity>
<TouchableOpacity activeOpacity={0.6}>
<View>
<Image style={styles.profile} source={profileView} />
</View>
</TouchableOpacity>
</View>
</View>
</View>
);
};
}
const FirstActivity_StackNavigator = createStackNavigator({
First: {
screen: Screen1,
navigationOptions: ({ navigation }) => ({
title: 'Demo Screen 1',
headerLeft: () => <Header navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
}
,
{
headerMode: "none"
}
);
const Screen2_StackNavigator = createStackNavigator({
Second: {
screen: Screen2,
navigationOptions: ({ navigation }) => ({
title: 'Demo Screen 2',
headerLeft: () => <Header navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
},
{
headerMode: "none"
}
);
const Screen3_StackNavigator = createStackNavigator({
Third: {
screen: Screen3,
navigationOptions: ({ navigation }) => ({
title: 'Demo Screen 3',
headerLeft: () => <Header navigationProps={navigation} />,
headerStyle: {
backgroundColor: '#FF9800',
},
headerTintColor: '#fff',
}),
},
});
const DrawerNavigator = createDrawerNavigator({
Screen1: {
screen: FirstActivity_StackNavigator,
navigationOptions: {
drawerLabel: 'Demo Screen 1',
},
},
Screen2: {
screen: Screen2_StackNavigator,
navigationOptions: {
drawerLabel: 'Demo Screen 2',
},
},
Screen3: {
screen: Screen3_StackNavigator,
navigationOptions: {
drawerLabel: 'Demo Screen 3',
},
},
});
const styles = StyleSheet.create({
header: {
width: '100%',
height: statusBarHeight,
backgroundColor: '#E6E3E2',
flexDirection: 'row',
},
headerContainer: {
height: 60,
backgroundColor: '#E6E3E2',
justifyContent: 'center',
alignItems: 'center'
},
imageHolder: {
flexDirection: "row",
justifyContent: 'space-between',
width: '95%'
},
menu: {
marginTop: 15,
width: 27,
height: 19,
resizeMode: "stretch"
},
logo: {
width: 140,
height: Platform.OS === 'ios' ? 50 : 50,
},
profile: {
marginTop: 3,
height: 38,
width: 35
}
});
const CreateDrawer = createAppContainer(DrawerNavigator);
export default Header;
App.js
import React, { Component } from "react";
import { StyleSheet, Text, View } from "react-native";
import Header from './components/Header';
export default class App extends Component {
render() {
return (
<View style={{flex:1}} >
<View style={{backgroundColor: 'blue'}}>
<Header />
</View>
</View>
);
}
}
Use export default withNavigation(Header); while exporting for a stack of navigations.

react-native-autocomplete result list not touchable

I have this implementation of a screen
import React, { Component } from 'react';
import { StyleSheet } from 'react-native';
import { Icon, View, Text, ListItem } from 'native-base';
import { createMaterialTopTabNavigator } from 'react-navigation';
import { connect } from 'react-redux';
import Autocomplete from 'native-base-autocomplete';
import EventsResults from './EventsResults';
import VehiclesResults from './VehiclesResults';
import { performSearch } from '../actions/search';
import Colors from '../../../util/Colors';
import GlobalStyle from '../../../util/GlobalStyle';
const styles = StyleSheet.create({
autocompleteContainer: {
zIndex: 800
}
});
const mapStateToProps = ({ searchResults }) => ({
searchResults
});
const SearchTabNavigatorStack = createMaterialTopTabNavigator(
{
EventsTab: {
screen: EventsResults,
navigationOptions: { tabBarLabel: 'Events' }
},
VehiclesTab: {
screen: VehiclesResults,
navigationOptions: { tabBarLabel: 'Vehicles' }
}
},
{
initialRouteName: 'EventsTab',
navigationOptions: () => ({
tabBarVisible: true
}),
swipeEnabled: true,
tabBarOptions: {
upperCaseLabel: false,
activeTintColor: Colors.defaultPrimaryColor,
inactiveTintColor: Colors.defaultPrimaryColor,
indicatorStyle: {
backgroundColor: Colors.defaultPrimaryColor,
},
tabStyle: {
height: 48,
alignItems: 'center',
justifyContent: 'center',
},
style: {
backgroundColor: Colors.primaryBackgroundColor,
},
statusBarStyle: 'light-content',
},
}
);
const filterData = (query) => {
const cars = [];
cars.push({ text: 'Chevrolet Trailblazer 2011' });
cars.push({ text: 'Chevrolet Spark 2011' });
cars.push({ text: 'Chevrolet Silverado 2011' });
cars.push({ text: 'Ford Explorer 2010' });
cars.push({ text: 'Ford Escape 2012' });
cars.push({ text: 'Ford Ecosport 2014' });
const result = (query === null || query.trim() === '') ? [] : cars.filter(car => car.text.indexOf(query) !== -1);
return result;
};
class HeaderComponent extends Component {
constructor(props) {
super(props);
this.state = { text: null };
}
render() {
const data = filterData(this.state.text);
return (
<View
style={{
flex: 0,
flexDirection: 'column',
justifyContent: 'space-between',
backgroundColor: Colors.primaryBackgroundColor
}}
>
<View
style={{
flex: 0,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
}}
>
<Text style={[GlobalStyle.textTitleStyle, { marginLeft: 10 }]}>search</Text>
<Icon active style={{ color: Colors.defaultPrimaryColor, margin: 10 }} name='ios-close' />
</View>
<View
style={{
flex: 0,
flexDirection: 'row',
justifyContent: 'space-evenly',
alignItems: 'center',
backgroundColor: Colors.defaultPrimaryColor,
marginLeft: 10,
marginRight: 10
}}
>
<Autocomplete
data={data}
containerStyle={styles.autocompleteContainer}
style={{ color: Colors.searchTextInput, backgroundColor: 'white' }}
onChangeText={(text) => this.setState({ text })}
renderItem={item => (
<ListItem style={{ zIndex: 900 }} onPress={() => this.setState({ text: item.text })}>
<Text>{item.text}</Text>
</ListItem>
)}
/>
</View>
</View>
);
}
}
const HeaderContainer = connect(mapStateToProps, { performSearch })(HeaderComponent);
class SearchScreen extends Component {
static router = SearchTabNavigatorStack.router;
static navigationOptions = ({ navigation }) => ({
header: <HeaderContainer />
});
render() {
return (
<SearchTabNavigatorStack navigation={this.props.navigation} />
);
}
}
export default connect(mapStateToProps, null)(SearchScreen);
It had to be this way to provide the ui visual representation that was designed (not my idea); the autocomplete component is working, the result list is displayed but the items in the list are not clickable
I supossed the zIndex property should fix this, but to no avail, and i am out of ideas
Any help or suggestions ?

this.props.navigation.navigate does not work in screen

In my app I have a choose language screen which I have registered in the stackNavigator but I cannot use this.props.navigation.navigate in it
this 'choose language screen' appears on app first launch
this is index.js
import {AppRegistry} from 'react-native';
import App from './App';
import ChooseLanguage from './screens/ChooseLanguage'
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => ChooseLanguage);
this is ChooseLanguage Screen so when pressing the touchable opacity
I am calling this.props.navigation.navigate('AppIntroScreen') but it is not working it is giving me this error:
undefined is not an object (evaluating _this2.props.navigation.navigate)
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
Image, SafeAreaView, TouchableOpacity,AsyncStorage
} from "react-native";
import {withNavigation} from 'react-navigation'
import i18n from 'i18next';
import { translate } from 'react-i18next';
import NavigationService from './NavigationService';
import AppIntroScreen from './AppIntroScreen'
class ChooseLanguage extends Component {
state = {
isArabic: false,
isEnglish: false,
switchLang: true,
languageSet:false
}
async onChangeLang(lang) {
i18n.changeLanguage(lang);
try {
await AsyncStorage.setItem('#APP:languageCode', lang);
} catch (error) {
console.log(` Hi Errorrrr : ${error}`);
}
console.log(i18n.dir());
this.setState(state => ({
switchLang: !state.switchLang,
}));
}
render() {
const {t,navigation} = this.props;
console.log(navigation)
return (
(this.state.switchLang ? <SafeAreaView style={styles.container}>
<Image source={require('../assets/lang.png')} />
<Text style={{ fontSize: 25, color: '#FF5252', marginTop: 20, fontFamily: 'Hanken-Book' }}>Choose Language</Text>
<View style={{ flexDirection: 'row', justifyContent: 'space-evenly' }}>
<TouchableOpacity onPress={() => this.setState({ isEnglish: true, isArabic: false })} style={{ marginVertical: 20, marginHorizontal: 20, padding: 10, borderBottomColor: this.state.isEnglish ? '#a8a8a8' : '#ffffff', borderBottomWidth: this.state.isEnglish ? 1 : 0 }}>
<Text style={{color:this.state.isEnglish?'#000000':'#A8A8A8'}}>English</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => this.setState({ isEnglish: false, isArabic: true })} style={{ marginVertical: 20, marginHorizontal: 20, padding: 10,borderBottomColor: this.state.isArabic ? '#a8a8a8' : '#ffffff', borderBottomWidth: this.state.isArabic ? 1 : 0 }}>
<Text style={{color:this.state.isArabic?'#000000':'#A8A8A8'}}>Arabic</Text>
</TouchableOpacity>
</View>
<TouchableOpacity onPress={() =>
{
if(this.state.isArabic){
this.onChangeLang('ar');
this.props.navigation.navigate('AppIntroScreen');
}else if(this.state.isEnglish){
this.onChangeLang('en');
this.props.navigation.navigate('AppIntroScreen');
}else{
alert('Please Choose a language')
}
}
} style={{ backgroundColor: '#FF5252', alignSelf: 'center', padding: 10, width: '40%', marginTop: 15,borderRadius:5 }}>
<Text style={{ color: '#FFF', fontSize: 18, fontWeight: '100', textAlign: 'center', fontFamily: 'Hanken-Book' }}>Let's Start</Text>
</TouchableOpacity>
<View style={{
position: 'absolute',
bottom: 0,
right: 1,
left: 1,
height: 50,
justifyContent: 'center', alignItems: 'center'
}}>
<Image source={require('../assets/l1.png')} style={{ width: 120, height: 25 }} />
</View>
</SafeAreaView>:<AppIntroScreen />)
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
bottom: 20
}
});
export default translate(['chooselanguage'], { wait: true })(ChooseLanguage);
even though I am registering all my screens in the StackNavigator
here is the code of App.js
const TabNav = createBottomTabNavigator({
HomeScreen: {
screen: HomeScreen,
},
Categories: {
screen: Categories,
},
Search: {
screen: Search,
},
Settings: {
screen: Settings,
},
}, {
tabBarOptions: {
activeTintColor: '#ff5252',
inactiveTintColor: 'grey',
style: {
backgroundColor: 'white',
borderTopWidth: 0,
shadowOffset: { width: 5, height: 3 },
shadowColor: 'black',
shadowOpacity: 0.5,
elevation: 5
}
}
})
const StacksOverTabs = createStackNavigator({
Root: {
screen: TabNav,
},
ChooseLanguage:{
screen: ChooseLanguage,
navigationOptions:{
}
},
ListingPerCategory: {
screen: ListingPerCategory,
navigationOptions: {
// title: 'Notifications',
},
},
ListingInformation: {
screen: ListingInformation,
navigationOptions: {}
},
SubscribeScreen: {
screen: SubscribeScreen,
navigationOptions: {}
},
AppIntroScreen: {
screen: AppIntroScreen,
navigationOptions: {}
},
OnboardingScreens: {
screen: OnboardingScreens,
navigationOptions: {}
},
ListingDetail: {
screen: ListingDetail,
navigationOptions: {}
},
Contact: {
screen: ContactScreen,
navigationOptions: {}
},
}, {
headerMode: 'none',
navigationOptions: {
headerVisible: false,
}
});
const WrappedStack = ({ t,navigation }) => {
return <StacksOverTabs screenProps={{ t,navigation}} />;
};
const ReloadAppOnLanguageChange = translate('common', {
bindI18n: 'languageChanged',
bindStore: false,
})(WrappedStack);
class App extends React.Component {
state = { notification: {}, timePassed: false }
componentDidMount() {
OneSignal.init('99471d55-8e89-49ef-a70f-47661c9f952b', { kOSSettingsKeyAutoPrompt: true })
OneSignal.addEventListener('received', this.onReceived);
OneSignal.addEventListener('opened', this.onOpened);
OneSignal.addEventListener('ids', this.onIds);
}
async retrieveItem(key) {
try {
const retrievedItem = await AsyncStorage.getItem(key);
const item = JSON.parse(retrievedItem);
return item;
} catch (error) {
console.log("error");
}
return
}
componentWillUnmount() {
OneSignal.removeEventListener('received', this.onReceived);
OneSignal.removeEventListener('opened', this.onOpened);
OneSignal.removeEventListener('ids', this.onIds);
}
onReceived(notification) {
console.log("Notification received: ", notification);
}
onOpened(openResult) {
console.log('Message: ', openResult.notification.payload.body);
console.log('Data: ', openResult.notification.payload.additionalData);
console.log('isActive: ', openResult.notification.isAppInFocus);
console.log('openResult: ', openResult);
}
onIds(device) {
console.log('Device info: ', device);
}
render() {
this.retrieveItem('appLaunched').then((goals) => {
console.log(goals)
}).catch((error) => {
//this callback is executed when your Promise is rejected
console.log('Promise is rejected with error: ' + error);
});
return <ReloadAppOnLanguageChange />
}
}
export default App;
You can access the navigation prop in any component(deeply nested) by composing withNavigation HOC (not available in v1). It's useful when you cannot pass the navigation prop into the component directly, or don't want to pass it in case of a deeply nested child.
import React from 'react';
import { Button } from 'react-native';
import { withNavigation } from 'react-navigation';
class MyBackButton extends React.Component {
render() {
return <Button title="Back" onPress={() => { this.props.navigation.goBack() }} />;
}
}
// withNavigation returns a component that wraps MyBackButton and passes in the
// navigation prop
export default withNavigation(MyBackButton);

React navigation How can I change the header navigation title dynamically for each tab?

I have created 3 screens which display as tabs on the createMaterialTopTabNavigator which is inside a stack navigator my issue is i dont know how to dynamically set Header title for each tab. currently setting the title to "welcome" applies to all the tabs. Any help please?
xxxxxx
xxxxxx
xxxxxx
xxxxxx
xxxxxx
import { LinearGradient } from 'expo';
import { Icon } from "native-base";
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { createMaterialTopTabNavigator, DrawerActions } from 'react-navigation';
import Home from '../TabNavigator/Home';
import MyProfile from '../TabNavigator/MyProfile';
import SelectAirtime from '../TabNavigator/SelectAirtime';
export default class TabNavigator extends React.Component {
static navigationOptions = ({ navigation, }) => {
return {
title: "Welcome",
headerLeft: (
<View style={{ padding: 10, }}>
<Icon style={{ color: '#fff', fontSize: 24 }} name='menu' type="MaterialCommunityIcons"
onPress={() => navigation.dispatch(DrawerActions.openDrawer())} />
</View>
),
headerBackground: (
<LinearGradient
colors={['#2acc55', '#10356c']}
style={{ flex: 1 }}
start={[0, 0]}
end={[1, 0]}
/>
),
headerTitleStyle: { color: '#fff' },
}
}
render() {
return (
<HomeScreenTabNavigator></HomeScreenTabNavigator>
);
}
}
const HomeScreenTabNavigator = createMaterialTopTabNavigator({
Home: {
screen: Home, navigationOptions: {
tabBarIcon: ({ tintColor }) => (<Icon style={{ color: 'white', fontSize: 24 }} name='home' type="MaterialCommunityIcons" />),
}
},
"Buy AirTime": {
screen: SelectAirtime, navigationOptions: {
tabBarIcon: ({ tintColor }) => (<Icon style={{ color: 'white', fontSize: 24 }} name='cards-outline' type="MaterialCommunityIcons" />),
}
},
"Account": {
screen: MyProfile, navigationOptions: {
tabBarIcon: ({ tintColor }) => (<Icon style={{ color: 'white', fontSize: 24 }} name='user' type="EvilIcons" />),
}
},
},
{
initialRouteName: 'Home',
tabBarPosition: 'bottom',
tabBarOptions: {
activeTintColor: 'white',
inactiveTintColor: '#f2f2f2',
labelStyle: {
fontSize: 9,
},
tabStyle: {
height: 60,
},
style: {
backgroundColor: '#1e3c72',
borderBottomColor: '#1e3c72',
},
indicatorStyle: {
height: 0,
},
showIcon: true,
}
}
)
Define TabNavigator:
import { LinearGradient } from 'expo';
import { Icon } from "native-base";
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { createMaterialTopTabNavigator, DrawerActions } from 'react-navigation';
import Home from '../TabNavigator/Home';
import MyProfile from '../TabNavigator/MyProfile';
import SelectAirtime from '../TabNavigator/SelectAirtime';
const HomeScreenTabNavigator = createMaterialTopTabNavigator({
Home: {
screen: Home,
navigationOptions: {
tabBarIcon: ({ tintColor, homeTitle }) => ( < Icon style = { { color: 'white', fontSize: 24 } } name = 'home'
type = "MaterialCommunityIcons" / > ),
tabBarLabel: homeTitle,
}
},
"Buy AirTime": {
screen: SelectAirtime,
navigationOptions: {
tabBarIcon: ({ tintColor, selectAirtimeTitle }) => ( < Icon style = { { color: 'white', fontSize: 24 } } name = 'cards-outline'
type = "MaterialCommunityIcons" / > ),
tabBarLabel: selectAirtimeTitle,
}
},
"Account": {
screen: MyProfile,
navigationOptions: {
tabBarIcon: ({ tintColor, myProfileTitle }) => ( < Icon style = { { color: 'white', fontSize: 24 } } name = 'user'
type = "EvilIcons" / > ),
tabBarLabel: myProfileTitle,
}
},
}, {
initialRouteName: 'Home',
tabBarPosition: 'bottom',
tabBarOptions: {
activeTintColor: 'white',
inactiveTintColor: '#f2f2f2',
labelStyle: {
fontSize: 9,
},
tabStyle: {
height: 60,
},
style: {
backgroundColor: '#1e3c72',
borderBottomColor: '#1e3c72',
},
indicatorStyle: {
height: 0,
},
showIcon: true,
}
})
export default HomeScreenTabNavigator;
use it:
<HomeScreenTabNavigator
screenProps={{
homeTitle: 'This home title',
selectAirtimeTitle: 'This airtime title',
myProfileTitle: 'This profile title',
}}
/>
I hope useful to you!