Related
How to pass the data to API?
//Parent Componet - in updateval function, i m trying get the selected values from dropdown but i am not getting to know how to get that.
import ElementDropdown from '../Components/ElementDropdown';
class ScanScreen extends Component {
constructor(props) {
super(props);
}
updatedVal=(item,value)=>{
console.log("hgfgf",item,value);
}
render() {
return (
<ElementDropdown text={'Country'} label={['Germany','India']} updatedVal={this.updatedVal}/>
<ElementDropdown text={'Store'} label={['Dusseldolf','Bangalore']} updatedVal={this.updatedVal}/>
)
}
}
export default ScanScreen;
//Child component - I m trying to send selected values from dropdown list to parent in updatedval.
import React, { useState } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Dropdown } from 'react-native-element-dropdown';
import BPText from './BPText';
import ThemeColors from '../themes/bp-themes/variables/themeColors';
const ElementDropdown = (props) => {
const { text, label,updatedVal } = props;
const [value, setValue] = useState(null);
const [isFocus, setIsFocus] = useState(false);
const data = [
{ label: label[0], value: "id1" },
{ label: label[1], value: "id2" },
];
return (
<View style={styles.container}>
<View style={styles.textContainer}>
<BPText type="Light" style={{ color: ThemeColors.themeColorYellow }}>
{text}
</BPText>
</View>
<View style={styles.dropContainer}>
<Dropdown
style={[styles.dropdown, isFocus && { borderColor: 'blue' }]}
selectedTextStyle={styles.selectedTextStyle}
iconStyle={styles.iconStyle}
placeholderStyle={styles.placeholderStyle}
data={data}
maxHeight={300}
labelField="label"
valueField="value"
item
placeholder={label[0]}
value={value}
onFocus={() => setIsFocus(true)}
onBlur={() => setIsFocus(false)}
onChange={item => {
setValue(item.value);
setIsFocus(false);
//setIsDefalut(false);
updatedVal(item,label[0],label[1]);
}}
/>
</View>
</View>
);
};
export default ElementDropdown;
const styles = StyleSheet.create({
container: {
borderBottomWidth: 0.5,
borderBottomColor: 'white',
flexDirection: 'row',
marginLeft: 40,
marginRight: 40,
marginTop: 10,
justifyContent: 'center',
alignItems: 'center',
},
textContainer:{
flex:1
},
dropContainer: {
flex: 2,
},
dropdown: {},
icon: {
marginRight: 5,
},
selectedTextStyle: {
color: 'white',
},
iconStyle: {
width: 20,
height: 20,
tintColor: 'white'
},
placeholderStyle:{
color:'white'
}
});
I am having difficulty of accessing parameters passed from component named NewsPageScreen.js. the parameters are passed to BrowserScreen.js. My app has Main Navigator component called MainTabNavigator.js that displays Bottom Tabs. The 'News' tab is connected to NewsPageScreen.js and this is where I am passing the the parameter to BrowserScreen.js but for some reason I am unable to access the parameters BrowserScreen.js, Can anyone help me see what I am getting wrong because it is giving me undefined. All my files are shown below:
MainTabNavigator.js
import React from 'react';
import { Ionicons } from '#expo/vector-icons';
import { TabBarBottom } from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs'
import { createAppContainer } from 'react-navigation'
import { createStackNavigator } from 'react-navigation-stack'
import NewsPageScreen from '../screens/NewsPageScreen';
import FavouriteScreen from '../screens/FavouriteScreen';
import SettingScreen from '../screens/SettingScreen';
import BrowserScreen from '../screens/BrowserScreen';
const Colors = {
tabIconDefault: '#ccc',
tabIconSelected: '#2f95dc'
}
const tabNavigator = createBottomTabNavigator({
News: createStackNavigator({
News: NewsPageScreen,
navigationOptions: ({ navigation }) => ({
title: 'News'
}),
}),
Favourite: createStackNavigator({
Favourite: FavouriteScreen,
navigationOptions: ({ navigation }) => ({
title: 'Favourite'
}),
}),
Setting: createStackNavigator({
Setting: SettingScreen,
navigationOptions: ({ navigation }) => ({
title: 'Setting'
}),
}),
Browser: createStackNavigator({
Browser: BrowserScreen,
navigationOptions: ({ navigation }) => ({
title: navigation.state.params.title
}),
}),
}, {
navigationOptions: ({ navigation }) => ({
tabBarIcon: ({ focused }) => {
const { routeName } = navigation.state;
let IconComponent = Ionicons ;
let iconName;
switch (routeName) {
case 'News':
//iconName = `ios-information-circle`;
iconName = focused ? 'ios-information-circle' : 'ios-information-circle-outline'
break;
case 'Favourite':
iconName = `ios-link`;
break;
case 'Setting':
iconName = `ios-options`;
}
return
<IconComponent
name={iconName}
size={28}
style={{marginBottom: -3}}
//color={tintColor}
color={focused ? Colors.tabIconSelected : Colors.tabIconDefault}
/>
},
}),
tabBarComponent: TabBarBottom,
tabBarPosition: 'bottom',
animationEnabled: false,
swipeEnabled: false,
});
const MainTabNavigator = createAppContainer(tabNavigator)
export default MainTabNavigator;
NewsPageScreen.js
import React, { Component } from 'react'
import { TouchableOpacity, View,StyleSheet,Text,SafeAreaView,} from 'react-native';
export default class NewsPageScreen extends Component {
state = {
links: [
{
title: 'Smashing Magazine',
url: 'https://www.smashingmagazine.com/articles/'
},
{
title: 'CSS Tricks',
url: 'https://css-tricks.com/'
},
],
};
handleButtonPress = (button) => {
const { url, title } = button;
this.props.navigation.navigate('BrowserScreen', { url, title });
}
renderButton = (button, index) => {
return (
<TouchableOpacity
key={index}
onPress={() => this.handleButtonPress(button)}
style={styles.button}
>
<Text style={styles.text}>{button.title}</Text>
</TouchableOpacity>
);
}
render() {
return (
<SafeAreaView style={styles.container}>
<View>
<Text style={styles.newsTitle}>Scan The Somali world News</Text>
</View>
<View style={styles.buttonList}>
{this.state.links.map(this.renderButton)}
</View>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
buttonList: {
flex: 1,
justifyContent: 'center',
},
button: {
margin: 10,
backgroundColor: '#c0392b',
borderRadius: 3,
padding: 10,
paddingRight: 30,
paddingLeft: 30,
},
text: {
color: '#fff',
textAlign: 'center',
},
newsTitle: {
color:'#000',
textAlign: 'center',
marginTop: 20
}
});
BrowserScreen.js
import React, { Component } from 'react'
import { WebView } from 'react-native-webview';
export default class BrowserScreen extends Component {
render() {
//console.log(navigation)
const { params } = this.props.navigation.state;
console.log(params)
return (
/**
* use the webview here to display the webpage
*/
<WebView source={{ uri: url }} />
)
}
}
App.js
import { StatusBar } from 'expo-status-bar';
import React, { useState } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import AppIntroSlider from "react-native-app-intro-slider";
import MainTabNavigatorp from './src/navigation/MainTabNavigator';
export default function App() {
return (
<View style={{flex: 1}}>
<MainTabNavigator />
</View>
);
}
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
paddingTop: 20,
alignItems: 'center',
justifyContent: 'center',
padding: 20
},
slide: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'blue',
},
image: {
width: 220,
height: 220,
marginVertical: 32,
},
description: {
color: 'rgba(255, 255, 255, 0.8)',
textAlign: 'center',
paddingLeft: 10,
paddingRight: 10,
fontSize: 18,
},
title: {
fontSize: 25,
color: 'white',
fontWeight: 'bold',
textAlign: 'center',
},
});
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.
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);
I am using the tab navigator in stack navigator ..when in tab navigator i move to next tab there a little bit pause then move to next tab...the code of index file is
import React, { Component } from 'react';
import { AppRegistry,Alert,ScrollView, Image, Dimensions,
Text,View,TouchableOpacity,StyleSheet} from 'react-native'
import Login from './login'
import SignUp from './signup'
import forget from './forget'
import Tabo from './DefaultTabBar'
import { StackNavigator,TabNavigator } from 'react-navigation';
import HomeButton from './HomeButton'
import ProfileScreen from './ProfileScreen'
import Granjur from './granjur'
const background=require("./flag/1.jpg");
export default class TabViewExample extends Component {
render(){
const { navigation } = this.props;
return(
<App navigation={ navigation }/>
);
}
}
const MyApp = TabNavigator({
Home: {
screen: HomeButton,
},
Notifications: {
screen: ProfileScreen,
},
},
{
swipeEnabled:false,
initialRouteName: 'Home',
tabBarOptions: {
activeTintColor: '#e91e63',
},
});
const Simple = StackNavigator({
Login: {
screen: Login,
},
signup: {
screen: SignUp,
},
forget:{
screen:forget
},
dashbord:{
screen:Granjur
}
});
AppRegistry.registerComponent('TabNavigator', () => Simple);
i also use scrollable tabView in that tab view also that problem occur..In second tab i have a swipable list view may be due to this error come how i resolv this the code for profile screen is that
import React, {
Component,
} from 'react';
import {
AppRegistry,
ListView,
StyleSheet,
Text,
TouchableOpacity,
TouchableHighlight,
View,
Alert,
Dimensions
} from 'react-native';
import { SwipeListView, SwipeRow } from 'react-native-swipe-list-view';
var alertMessage="You want to Delete it";
var alertMessage1='why press it'
var v1=1.0;
const wid=Dimensions.get('window').width;
export default class App extends Component {
constructor(props) {
super(props);
this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
basic: true,
listViewData: Array(5).fill('').map((_,i)=>`item #${i}`)
};
}
deleteRow(secId, rowId, rowMap) {
rowMap[`${secId}${rowId}`].closeRow();
const newData = [...this.state.listViewData];
newData.splice(rowId, 1);
this.setState({listViewData: newData});
}
// undoRow(rowId) {
// const newData = [...this.state.listViewData];
// this.setState({listViewData: newData});
// this.setState({listViewData: newData});
// }
render() {
return (
<SwipeListView
dataSource={this.ds.cloneWithRows(this.state.listViewData)}
renderRow={ data => (
<TouchableHighlight
onPress={ _ => Alert.alert(
'Alert Title',
alertMessage1,
) }
style={styles.rowFront}
underlayColor={'#AAA'}
>
<Text>I am {data} in a SwipeListView</Text>
</TouchableHighlight>
)}
renderHiddenRow={ (data, secId, rowId, rowMap) => (
<View style={styles.rowBack}>
<TouchableOpacity style={{backgroundColor:'#2c3e50',alignItems: 'center',bottom: 0,justifyContent: 'center',position: 'absolute',top: 0,width: 75}}
onPress={ _ => rowMap[ `${secId}${rowId}` ].closeRow() } >
<Text style={styles.backTextWhite}>Undo</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.backRightBtn, styles.backRightBtnRight]}
onPress={ _ => Alert.alert(
'Are You Sure',alertMessage,
[{text: 'OK', onPress: () =>this.deleteRow(secId, rowId, rowMap)},
{text: 'Cancel',}]
) }>
<Text style=
{styles.backTextWhite}>Delete</Text>
</TouchableOpacity>
</View>
)}
leftOpenValue={wid}
rightOpenValue={-wid}
disableLeftSwipe={true}
/>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
flex: 1
},
standalone: {
marginTop: 30,
marginBottom: 30,
},
standaloneRowFront: {
alignItems: 'center',
backgroundColor: '#CCC',
justifyContent: 'center',
height: 50,
},
standaloneRowBack: {
alignItems: 'center',
backgroundColor: '#8BC645',
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
padding: 15
},
backTextWhite: {
color: '#FFF'
},
rowFront: {
alignItems: 'center',
backgroundColor: '#CCC',
borderBottomColor: 'black',
borderBottomWidth: 1,
justifyContent: 'center',
height: 50,
},
rowBack: {
alignItems: 'center',
backgroundColor: '#DDD',
flex: 1,
flexDirection: 'row',
//justifyContent: 'space-between',
paddingLeft: 15,
},
backRightBtn: {
alignItems: 'center',
bottom: 0,
justifyContent: 'center',
position: 'absolute',
top: 0,
width: 75
},
backRightBtnLeft: {
backgroundColor: 'blue',
//right: 75
},
backRightBtnRight: {
backgroundColor: '#2c3e50',
right: 0
},
controls: {
alignItems: 'center',
marginBottom: 30
},
switchContainer: {
flexDirection: 'row',
justifyContent: 'center',
marginBottom: 5
},
switch: {
alignItems: 'center',
borderWidth: 1,
borderColor: 'black',
paddingVertical: 10,
width: 100,
}
});
App.navigationOptions = {
title: 'Signup Screen',
headerVisible:false
};
AppRegistry.registerComponent('TabNavigator', () => App);
How i remove this pause plz tell me early as soon as possible..Thanks