Parameters not transfering through screens - reactjs

I want to pass some parameters through different screens. I had successfully done it before in different parts of the application, but for some reason, it is not working all of a sudden, and I am not sure why?
navigator:
import { createStackNavigator } from '#react-navigation/stack'
import HomeScreen from '../screens/HomeScreen';
import FilterScreen from '../screens/HomeScreens/FilterScreen';
import SortScreen from '../screens/HomeScreens/SortScreen';
import { SearchFilterSortContextProvider } from '../context/SearchFilterSortContext';
const StackNav = createStackNavigator();
const HomeStackNav = () => {
return (
<StackNav.Navigator initialRouteName='HomeScreen' screenOptions={{headerShown: false}}>
<StackNav.Screen name="HomeScreen" component={HomeScreen}/>
<StackNav.Screen name="FilterHomeScreen" component={FilterScreen}/>
<StackNav.Screen name="SortHomeScreen" component={SortScreen}/>
</StackNav.Navigator>
)
}
export default HomeStackNav
HomeScreen:
import React, { useEffect} from 'react'
import {View, Text, StyleSheet} from 'react-native'
import SearchAndFilterComponent from '../components/HomeScreen/SearchAndFilterComponent';
import ResultsComponent from '../components/HomeScreen/ResultsComponent';
import { SearchFilterSortContextProvider } from '../context/SearchFilterSortContext';
const HomeScreen = ({navigation, route}) => {
useEffect(() => {
const unsubscribe = navigation.addListener('focus', () => {
console.log(route.params)
})
return unsubscribe
}, [navigation])
return (
<SearchFilterSortContextProvider>
<View style={styles.screen}>
<SearchAndFilterComponent/>
<View style={styles.fullSplit}></View>
<ResultsComponent />
</View>
</SearchFilterSortContextProvider>
)
}
const styles = StyleSheet.create({
fullSplit: {
width: '100%',
height: 2,
backgroundColor: 'black'
}
})
export default HomeScreen
Sort Screen Component making the call:
import React, { useContext } from 'react'
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native'
import { Feather } from '#expo/vector-icons'
import { useNavigation } from '#react-navigation/native'
import { SearchFilterSortContext } from '../../context/SearchFilterSortContext'
const SortOptionsComponent = () => {
const {sort, setSort} = useContext(SearchFilterSortContext)
const navigation = useNavigation()
return (
<View>
<TouchableOpacity onPress={() => {navigation.navigate('HomeScreen', {sort:'Homes_for_You'})}} style={styles.row}>
<Text style={styles.text}>Homes For You</Text>
{
sort === 'Homes_for_You' ? <Feather name='check' color={'black'} size={20}/> : null
}
</TouchableOpacity>
<TouchableOpacity onPress={() => {navigation.navigate('HomeScreen', {sort:'Newest'})}} style={styles.row}>
<Text style={styles.text}>Newest</Text>
{
sort === 'Newest' ? <Feather name='check' color={'black'} size={20}/> : null
}
</TouchableOpacity>
<TouchableOpacity onPress={() => {navigation.navigate('HomeScreen', {sort:'Price_High_Low'})}} style={styles.row}>
<View style={styles.rowIcon}>
<Text style={[styles.text, styles.price]}>Price</Text>
<Feather name='arrow-down' size={22} color={'black'}/>
</View>
{
sort === 'Price_High_Low' ? <Feather name='check' color={'black'} size={20}/> : null
}
</TouchableOpacity>
<TouchableOpacity onPress={() => {navigation.navigate('HomeScreen', {sort:'Price_Low_High'})}} style={styles.row}>
<View style={styles.rowIcon}>
<Text style={[styles.text, styles.price]}>Price</Text>
<Feather name='arrow-down' size={22} color={'black'}/>
</View>
{
sort === 'Price_Low_High' ? <Feather name='check' color={'black'} size={20}/> : null
}
</TouchableOpacity>
<TouchableOpacity onPress={() => {navigation.navigate('HomeScreen', {sort:'Bedrooms'})}} style={styles.row}>
<Text style={styles.text}>Bedrooms</Text>
{
sort === 'Bedrooms' ? <Feather name='check' color={'black'} size={20}/> : null
}
</TouchableOpacity>
<TouchableOpacity onPress={() => {navigation.navigate('HomeScreen', {sort:'Bathrooms'})}} style={styles.row}>
<Text style={styles.text}>Bathrooms</Text>
{
sort === 'Bathrooms' ? <Feather name='check' color={'black'} size={20}/> : null
}
</TouchableOpacity>
<TouchableOpacity onPress={() => {navigation.navigate('HomeScreen', {sort:'Square_Feet'})}} style={styles.row}>
<Text style={styles.text}>Sqft.</Text>
{
sort === 'Square_Feet' ? <Feather name='check' color={'black'} size={20}/> : null
}
</TouchableOpacity>
<TouchableOpacity onPress={() => {navigation.navigate('HomeScreen', {sort:'Lot_Size'})}} style={styles.row}>
<Text style={styles.text}>Lot Size</Text>
{
sort === 'Lot_Size' ? <Feather name='check' color={'black'} size={20}/> : null
}
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
nav: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center'
},
text: {
fontSize: 17,
fontWeight: '500'
},
row: {
paddingVertical: 12,
borderBottomWidth: 1,
borderBottomColor: 'lightgrey',
paddingHorizontal: 8,
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
},
rowIcon: {
display: 'flex',
flexDirection: 'row',
alignItems: 'center'
},
price: {
marginRight: 4
}
})
export default SortOptionsComponent
When it runs navigation.navigate('HomeScreen', {sort: 'Homes_for_You'}), it does go back to the home screen but prints this:
{"key": "HomeScreen-woUXGRPlOtjfIhEY51Ew1", "name": "HomeScreen", "params": undefined}

Change your function in HomeScreen and SortScreen be like:
HomeScreen:
React.useEffect(() => {
if (route.params) {
console.log(route.params)
}
}, [route.params]);
SortScreen:
<TouchableOpacity
...
onPress={() => {
navigation.navigate({
name: 'HomeScreen',
params: { sort: 'Newest' },
merge: true,
});
}}
>
...
</TouchableOpacity>
More information: https://reactnavigation.org/docs/params/#passing-params-to-a-previous-screen

Related

Invalid hook call react hooks

Hi I am a new React user and I am trying to add the following component to an app I'm developing:
import React, { useState, useEffect, Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import { Camera, CameraType } from 'expo-camera';
function InAppCamera() {
const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(CameraType.back);
useEffect(() => {
(async () => {
const { status } = await Camera.requestCameraPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
if (hasPermission === null) {
return <View />;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={styles.container}>
<Camera style={styles.camera} type={type}>
<View style={styles.buttonContainer}>
<TouchableOpacity
style={styles.button}
onPress={() => {
setType(type === CameraType.back ? CameraType.front : CameraType.back);
}}>
<Text style={styles.text}> Flip </Text>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
camera: {
flex: 1,
},
buttonContainer: {
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
margin: 20,
},
button: {
flex: 0.1,
alignSelf: 'flex-end',
alignItems: 'center',
},
text: {
fontSize: 18,
color: 'white',
},
});
export default InAppCamera;
I am trying to reference this component in another .js file as seen below:
<FAB style={styles.fab} small icon="camera" onPress={InAppCamera} />
I get an error for an invalid hook call. Any suggestions would be great thank you so much!
//You can get some idea from the given sample.
const [showCamera, setCamera] = useState(false);
return <View>
/*Other Code If any */
<FAB style={styles.fab} small icon="camera" onPress={() => setCamera(!showCamera)} />
{showCamera ? <InAppCamera /> : null}
/*Other Code If any */
</View>

set state required double click

I have a useState hook that stores if a menu should be shown or not, in my jsx render I have a touchableOpacity that when I change it, it should update my state and show the menu, but the state does not update unless I give it click more than once to the touchable.
this error happens with the expenseActivitie state, when updating it within the showExpenses function.
Screen:
import React, { useContext, useEffect, useState } from 'react'
import { Dimensions, Text, TouchableOpacity, View } from 'react-native'
import { StackScreenProps } from '#react-navigation/stack';
import { RootStackParams } from '../../navigator/Navigator';
import { commonStyles } from '../../styles/commonStyles';
import { ThemeContext } from '../../contexts/theme/ThemeContext';
import LinearGradient from 'react-native-linear-gradient';
import { FontAwesomeIcon } from '#fortawesome/react-native-fontawesome';
import { faExclamationCircle, faFilter } from '#fortawesome/free-solid-svg-icons';
import { ExpenseActivitiesRQ } from '../../interfaces/viatics/ExpenseActivitiesRQ';
import { useActivities } from '../../hooks/viatics/useActivities';
import { AuthContext } from '../../contexts/auth/AuthContext';
import { FlatList, ScrollView } from 'react-native-gesture-handler';
import { GActivities } from '../../interfaces/viatics/GActivities';
import Icon from 'react-native-vector-icons/Ionicons'
import Moment from 'moment';
import { setStateActivity } from '../../helpers/viatics/setStateActivity';
import { setStateColor } from '../../helpers/viatics/setStateColor';
import { ExpensesScreen } from './ExpensesScreen';
import { ActivityIndicator } from 'react-native';
import { Col, Grid, Row } from 'react-native-easy-grid';
import { activitiesStyles } from '../../styles/activitiesStyles';
import { MenuActivity } from '../../components/viatics/menuActivity';
import { GExpenses } from '../../interfaces/viatics/GExpenses';
interface Props extends StackScreenProps<RootStackParams, 'ActivitiesListScreen'>{};
export const ActivitiesListScreen = ( { route, navigation }: Props ) => {
const { userData } = useContext( AuthContext );
const request: ExpenseActivitiesRQ = {
IDUser: userData.IDUser,
IDEntity: userData.IDEntityDefault,
excludeImages: true
};
const type = route.params.type;
const { loading, activitiesList } = useActivities( type, request );
const { theme: { colors, secondary, buttonText } } = useContext( ThemeContext );
const [expenseActivitie, setExpenseActivitie] = useState({
showExpense: false,
currentIndex: -1
});
const [menus, setMenus] = useState({
menuExpense: false,
menuActivity: false
});
const [currentExpense, setCurrentExpense] = useState({
menuExpense: false,
data: new GExpenses()
});
useEffect(() => {
switch( type ) {
case 'allActivities':
navigation.setOptions({
title: 'Actividades Generales'
});
break;
case 'pendingApprove':
navigation.setOptions({
title: 'Pendientes por Aprobar'
});
break;
case 'pendingLegalize':
navigation.setOptions({
title: 'Pendientes por Legalizar'
});
break;
default:
navigation.setOptions({
title: 'Activitidades'
});
break;
}
}, []);
const renderActivitieCard = ( activitie: GActivities, index: number ) => {
const bottomPadding: number = ( activitiesList.ListActivities.length === ( index + 1 ) && ( menus.menuActivity || menus.menuExpense ) ) ? 80 : 0;
return (
<>
<View style={{ paddingBottom: bottomPadding }}>
<View style={{ ...activitiesStyles.datesContainer, backgroundColor: colors.primary,}}>
<Text style={{ color: buttonText, fontSize: 12, marginLeft: 4 }}>
{ Moment(activitie.DateSta).format('DD/MMMM/YYYY') }
</Text>
<Icon
name="repeat"
color={ buttonText }
size={ 30 }
/>
<Text style={{ color: buttonText, fontSize: 12 }}>
{ Moment(activitie.DateEnd).format('DD/MMMM/YYYY') }
</Text>
<View style={{ ...activitiesStyles.activityState, backgroundColor: setStateColor(activitie.State) }}>
<Text style={{ textAlign: 'center', color: buttonText }}>{ setStateActivity(activitie.State) }</Text>
</View>
</View>
<View style={{ borderWidth: 2, marginBottom: 10, borderColor: colors.primary, borderBottomLeftRadius: 10, borderBottomRightRadius: 10 }}>
<View style={{ marginTop: 10, marginBottom: 5 }}>
<View style={{ ...activitiesStyles.dataContainer, }}>
<Text style={{color: colors.text, fontWeight: 'bold'}}>Pasajero: </Text>
<Text style={{color: colors.text}}>{ activitie.UserName }</Text>
</View>
<View style={{ ...activitiesStyles.dataContainer }}>
<Text style={{color: colors.text, fontWeight: 'bold'}}>Actividad: </Text>
<Text style={{color: colors.text}}>{ activitie.Description }</Text>
</View>
<View style={{ ...activitiesStyles.dataContainer }}>
<Text style={{color: colors.text, fontWeight: 'bold'}}>Gastos Registrados: </Text>
<Text style={{color: colors.text}}>{ activitie.countExpenses }</Text>
</View>
<View style={{ ...activitiesStyles.dataContainer }}>
<Text style={{color: colors.text, fontWeight: 'bold'}}>Registrado: </Text>
<Text style={{color: colors.text}}>{ activitie.totalExpense } de { activitie.Budget } </Text>
</View>
<View style={{ flex: 1, flexDirection: 'row', justifyContent: 'space-around' }}>
<TouchableOpacity
onPress={ () => showExpenses(index) }
style={{
...commonStyles.entireButton,
}}>
<LinearGradient
colors={[colors.primary, secondary]}
style={ commonStyles.smallButton }
>
<Text style={[commonStyles.buttonText, {
color: buttonText
}]}> Ver Gastos </Text>
</LinearGradient>
</TouchableOpacity>
<TouchableOpacity
onPress={ () => navigation.navigate('RegisterExpensesScreen') }
style={{
...commonStyles.entireButton,
}}>
<LinearGradient
colors={[colors.primary, secondary]}
style={ commonStyles.smallButton }
>
<Text style={[commonStyles.buttonText, {
color: buttonText
}]}> Adicionar Gasto </Text>
</LinearGradient>
</TouchableOpacity>
<TouchableOpacity
onPress={ () => setMenus({
...menus,
menuActivity: !menus.menuActivity
})}
style={{
...commonStyles.entireButton,
}}>
<LinearGradient
colors={[colors.primary, secondary]}
style={ commonStyles.smallButton }
>
<Text style={[commonStyles.buttonText, {
color: buttonText
}]}> + Opciones </Text>
</LinearGradient>
</TouchableOpacity>
</View>
{ (expenseActivitie.showExpense === false && expenseActivitie.currentIndex === index ) &&
<ExpensesScreen currentActivity={ activitie } menus={ menus } parentCallBack= { handleCallBack } />
}
</View>
</View>
</View>
</>
)
}
const showExpenses = (index: number) => {
setExpenseActivitie({
...expenseActivitie,
showExpense: !expenseActivitie.showExpense,
currentIndex: index
})
}
const handleCallBack = (childData: GExpenses) => {
console.log('childData', childData);
setCurrentExpense({
...currentExpense,
data: childData,
menuExpense: true,
})
}
return (
<>
<View style={{
...commonStyles.container,
alignItems: 'stretch',
bottom: 50,
}}>
<Text style={{
...commonStyles.title,
color: colors.primary,
marginBottom: 10
}}>
Actividades de Gastos
</Text>
<View style={ commonStyles.rightButtonContainer }>
<TouchableOpacity
disabled={( activitiesList.ListActivities.length > 0) ? false : true }
onPress={ () => navigation.navigate('FilterActivitiesScreen') }
style={commonStyles.rightButton}>
<LinearGradient
colors={[colors.primary, secondary]}
style={{
...commonStyles.rightButton,
flexDirection: 'row'
}}
>
<FontAwesomeIcon
style={{
color: buttonText
}}
icon={ faFilter }
size={20} />
<Text style={[commonStyles.buttonText, {
color:'#fff'
}]}>Filtrar</Text>
</LinearGradient>
</TouchableOpacity>
</View>
{
!loading &&
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator
size="large"
animating={ true }
color={ colors.primary }
></ActivityIndicator>
</View>
}
{
( loading && activitiesList.ListActivities.length > 0 )
&&
<View style={{ marginTop: 10, flex: 1, width: '100%' }}>
<FlatList
data={ activitiesList.ListActivities }
keyExtractor={ (activie: GActivities) => activie.IDGroup }
renderItem={ ({ item, index }) => renderActivitieCard( item, index ) }
/>
</View>
}
{
( loading && activitiesList.ListActivities.length === 0 )
&&
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center', }}>
<FontAwesomeIcon
icon={ faExclamationCircle }
color={ colors.primary }
size={ 100 }
/>
<Text style={{
...commonStyles.title,
fontSize: 25,
color: colors.primary,
marginBottom: 10
}}>
No se encontraron Actividades
</Text>
</View>
}
</View>
{ menus.menuActivity &&
<MenuActivity />
}
</>
)
}
I appreciate any help
setExpenseActivitie( prev => {
...prev,
showExpense: !expenseActivitie.showExpense,
currentIndex: index
})
Try to modify your showexpenses function to look this.

store.dispatch not updating props when called from outside of class

store.js
import AsyncStorage from "#react-native-community/async-storage";
import { createStore, applyMiddleware } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import { createLogger } from "redux-logger";
import thunk from "redux-thunk";
import reducers from "../reducers";
const logger = createLogger({
// ...options
});
const persistedReducer = persistReducer(persistConfig, reducers);
export default () => {
let store = createStore(persistedReducer, {}, applyMiddleware(thunk, logger));
let persistor = persistStore(store);
return { store, persistor };
};
PathexploredTab.js
import * as React from "react";
import {
View,
StyleSheet,
Text,
Dimensions,
TouchableOpacity,
Alert,
Platform,
Image
} from "react-native";
import { TabView, SceneMap, TabBar } from "react-native-tab-view";
import { Config } from "#common";
import { connect } from "react-redux";
import { compose } from "redux";
import { Dropdown } from "react-native-material-dropdown";
import { Field, reduxForm } from "redux-form";
import { ScrollView } from "react-native-gesture-handler";
import { Actions } from "react-native-router-flux";
import Icon from "react-native-vector-icons/Feather";
import {
searchImmipaths,
isKeepData,
backToInitialState,
continueFromPrevious,
fetchDynamicFacts,
pathExplorerTutorial
} from "../actions/path.actions";
import { checkConnection } from "../service/checkConnection";
import Loader from "./Loader";
import { colors, normalize, family, Images } from "#common";
import ResponsiveImage from 'react-native-responsive-image';
import { RFValue } from "react-native-responsive-fontsize";
import RNPicker from "rn-modal-picker";
import * as Animatable from 'react-native-animatable';
import UserinfoPopUp from "./../pages/UserinfoPopUp";
import { updateUserDetails, getUserDetails } from "../actions/auth.actions";
import AsyncStorage from "#react-native-community/async-storage";
import { copilot, walkthroughable, CopilotStep } from 'react-native-copilot';
import { StepNumberComponent } from "./../pages/newProfileScreen";
import persist from "./../config/store";
import Reactotron from 'reactotron-react-native'
const WalkthroughableImage = walkthroughable(Image);
const WalkthroughableText = walkthroughable(Text);
const WalkthroughableView = walkthroughable(View);
const WalkthroughableTouch = walkthroughable(TouchableOpacity);
const persistStore = persist();
const TooltipComponent = ({
isFirstStep,
isLastStep,
handleNext,
handlePrev,
handleStop,
labels,
currentStep,
}) => {
const handleDiscardTutorial = () => {
Alert.alert(
'',
'are you sure you don’t want a tutorial on how to use the app?',
[
{
text: 'yes',
onPress: () => {AsyncStorage.setItem('DontShowTutorial', JSON.stringify(true)), handleStop()}
},
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel'
},
],
{ cancelable: false }
);
}
return (
<View style={styles.tooltipContainer}>
<Text testID="stepDescription" style={styles.tooltipText}>{currentStep.text}</Text>
<View style={[styles.bottomBar]}>
{
!isFirstStep ?
<TouchableOpacity style={styles.toolTipButton} onPress={handlePrev}>
<Text style={styles.toolTipButtonText}>{'Previous'}</Text>
</TouchableOpacity>
: null
}
{
!isLastStep ?
<TouchableOpacity style={styles.toolTipButton} onPress={handleNext}>
<Text style={styles.toolTipButtonText}>{'Next'}</Text>
</TouchableOpacity> :
<TouchableOpacity style={styles.toolTipButton} onPress={handleStop}>
<Text style={styles.toolTipButtonText}>{'Finish'}</Text>
</TouchableOpacity>
}
<TouchableOpacity onPress={() => persistStore.store.dispatch(pathExplorerTutorial('bbv'))}>
<Text style={styles.toolTipButtonText}>Go</Text>
</TouchableOpacity>
<TouchableOpacity onPress={handleDiscardTutorial}>
<Text style={styles.toolTipButtonText}>Do not show tutorial</Text>
</TouchableOpacity>
</View>
</View>
);
}
const window = Dimensions.get("window");
var width = window.width;
var height = window.height;
var immigrationInterst = [];
var countryIntrest = [];
let countryIntrestNow = [];
var FirstRoute = () => <View style={[{ height: height }]} />;
let disableButton = false;
var lastSearchedCountries = [];
var SecondRoute = () => <View style={[{ height: height }]} />;
class PathexploredTab extends React.Component {
constructor(props) {
super(props);
this.imageMap = ['', Images.studyImage, Images.workImage, Images.residencyImage, Images.tourismImage];
this.state = {
isloading: false,
buttonone: false,
immibut1: false,
immibut2: false,
immibut3: false,
immibut4: false,
userInfoPopUpVisible: false,
countrybut1: false,
countrybut2: false,
countrybut3: false,
countrybut4: false,
filedsToShow: [],
countrybut5: false,
countrybut6: false,
selectedval: "Select the Country",
index: 0,
routes: [
{ key: "first", title: "Select Goals" },
{ key: "second", title: "Select Countries" }
],
checkconnection: false,
errorMessage: "",
isItemSelected: true,
currentlySelectedItemIndex: -1,
isItemChecked: true,
checkboxData: ""
};
}
componentDidUpdate = (nextProps) => {
Reactotron.log('=====', nextProps.userPressedGo)
}
componentWillReceiveProps = (nextProps) => {
}
componentWillMount = async() => {
const {
getUser: { userDetails },
authData: { token }
} = this.props;
this.props.dispatch(getUserDetails(userDetails.userid, token))
}
componentDidMount() {
setTimeout(() => {
this.props.start();
}, 1000);
immigrationInterst = [];
countryIntrest = [];
countryIntrestNow = [];
const {
getUser: { userDetails }
} = this.props;
}
callProceed = () => {
const {
isItemSelected,
currentlySelectedItemIndex,
isItemChecked
} = this.state;
if (isItemSelected) {
Alert.alert("Immigreat", "Please select any goal");
return;
}
const lastGoal = this.props.immigationInterest[0]
//This is a bit of a hacky fix but it works.
let allPrevCountriesFound = lastSearchedCountries.every(ai => countryIntrestNow.includes(ai))
&& (lastSearchedCountries.length == countryIntrestNow.length);
//We want to clear and search when:
//a) There is no exploration id
//b) Even if there is an exploration id but the lastGoal or last countries dont match
//Note: We make one exception for if exploration id exists but the lastSearchedCountries is just an empty list
let noExplorationId = (this.props.explorationId === "");
let countryGoalDontMatch = (lastGoal != currentlySelectedItemIndex || !allPrevCountriesFound);
let isProceedException = (lastSearchedCountries.length == 0 && !noExplorationId);
noExplorationId || (!noExplorationId && countryGoalDontMatch && !isProceedException)
?
this.clearAndSearch()
: Alert.alert(
"Immigreat",
"Previous exploration found. Would you like to continue?",
[
{
text: "START FROM BEGINNING",
onPress: () => {
this.props.dispatch(continueFromPrevious(0));
this.props.dispatch(backToInitialState());
this.props.dispatch(isKeepData(false));
this._searchData();
},
style: "cancel"
},
{
text: "CONTINUE",
onPress: () => {
lastSearchedCountries = [...countryIntrest];
this.props.dispatch(isKeepData(true));
this.props.didTapOnSearch();
}
},
{
text: "Cancel",
onPress: () => console.log("Canceled"),
style: "cancel"
}
],
{ cancelable: false }
);
}
_onPressBackButton = () => {
this.setState(
{
isItemSelected: true,
currentlySelectedItemIndex: -1,
isItemChecked: false
},
() => {
setTimeout(() => {
this.intialLoadValues();
//this.setState({ isItemSelected: true });
}, 0);
}
);
}
extraOptionsRefresh() {
const { currentlySelectedItemIndex, isItemChecked } = this.state;
this.setState({ isItemChecked: !isItemChecked })
switch (currentlySelectedItemIndex) {
case 1:
this.setState({checkBoxData:
"Do you want to explore options you may have after your studies?"});
break;
case 2:
this.setState({checkBoxData:
"Do you want to explore other goal options (such as studies) that can lead to work options?"});
break;
case 3:
this.setState({checkBoxData:
"Do you want to explore other goal options (such as studies or work) that could lead to permanent residency in the future?"});
break;
case -1:
this.setState({checkBoxData: ""});
break;
}
}
intialLoadValues() {
const { currentlySelectedItemIndex, isItemChecked } = this.state;
/*var checkBoxData = "";
switch (currentlySelectedItemIndex) {
case 1:
checkBoxData =
"Do you want to explore options you may have after your studies?";
break;
case 2:
checkBoxData = "Do you want to explore other goal options (such as studies) that can lead to work options?";
break;
case 3:
checkBoxData =
"Do you want to explore other goal options (such as studies or work) that could lead to permanent residency in the future?";
break;
case 4:
checkBoxData = "";
break;
}*/
FirstRoute = () => (
<ScrollView style={{ flex: 1, backgroundColor: "white" }}>
<Animatable.View animation="fadeIn" duration={1200} style={{ flex: 1 }}>
<View
style={{
backgroundColor: "#DBDDDF",
alignItems: "center",
justifyContent: "center",
flex: 1
}}
>
<View style={{ padding: 20 }}>
<Text
style={{
textAlign: "center",
fontFamily: "SourceSansPro-Semibold",
color: "#2C393F",
fontSize: RFValue(12)
}}
>
Select the Immigration goal that you would be interested in
exploring
</Text>
<Text
style={{
textAlign: "center",
color: "#008BC7",
fontFamily: "SourceSansPro-Regular",
fontSize: RFValue(10)
}}
>
You can select/deselect ONLY one goal at a time by clicking the buttons. This is so we can help you hone your search!
</Text>
</View>
</View>
{(this.state.isItemSelected && this.state.currentlySelectedItemIndex < 0) ? (
<View style={{ marginTop: 30 }}>
{/*<Animatable.View animation="fadeIn" duration={1200} style={{ flexGrow: 1, justifyContent: 'center', alignItems: 'center', flexDirection: 'row' }}>*/}
<View style={styles.custombuttonView}>
<View style={{ width: "50%" }}>
<CopilotStep text="Select Your goals" order={1} name="study">
<WalkthroughableTouch
testID={`${Config.immigerat[0].code + 'button'}`}
onPress={() =>
this._immigreateIntrest(Config.immigerat[0].code)
}
style={
this.state.immibut1
? styles.selectedbutton
: styles.buttonstyleview
}
>
<WalkthroughableText
style={
this.state.immibut1
? styles.selectedbuttontext
: styles.buttonstyletext
}
>
{Config.immigerat[0].value}
</WalkthroughableText>
</WalkthroughableTouch>
</CopilotStep>
</View>
<View style={{ width: "50%" }}>
<TouchableOpacity
testID={`${Config.immigerat[1].code + 'button'}`}
onPress={() =>
this._immigreateIntrest(Config.immigerat[1].code)
}
style={
this.state.immibut2
? styles.selectedbutton
: styles.buttonstyleview
}
>
<Text
style={
this.state.immibut2
? styles.selectedbuttontext
: styles.buttonstyletext
}
>
{Config.immigerat[1].value}
</Text>
</TouchableOpacity>
</View>
</View>
<View style={styles.custombuttonView}>
<View style={{ width: "50%" }}>
<TouchableOpacity
testID={`${Config.immigerat[2].code + 'button'}`}
onPress={() =>
this._immigreateIntrest(Config.immigerat[2].code)
}
style={
this.state.immibut3
? styles.selectedbutton
: styles.buttonstyleview
}
>
<Text
style={
this.state.immibut3
? styles.selectedbuttontext
: styles.buttonstyletext
}
>
{Config.immigerat[2].value}
</Text>
</TouchableOpacity>
</View>
<View style={{ width: "50%" }}>
<TouchableOpacity
testID={`${Config.immigerat[3].code + 'button'}`}
onPress={() =>
this._immigreateIntrest(Config.immigerat[3].code)
}
style={
this.state.immibut4
? styles.selectedbutton
: styles.buttonstyleview
}
>
<Text
style={
this.state.immibut4
? styles.selectedbuttontext
: styles.buttonstyletext
}
>
{Config.immigerat[3].value}
</Text>
</TouchableOpacity>
</View>
</View>
{/*</Animatable.View>*/}
</View>
) : (
<View style={{ flex: 0.75, marginTop: 30 }}>
{/*<Animatable.View animation="fadeIn" duration={1200}>*/}
<View style={{ flexDirection: 'row', alignContent: 'center' }}>
<TouchableOpacity testID='goBackButton'
onPress={this._onPressBackButton} style={{ padding: 10 }} >
<View style={{ width: 80 }}>
<Icon name="chevron-left" size={30} color="black" />
</View>
</TouchableOpacity>
{<TouchableOpacity
onPress={() => this._immigreateIntrest("null")}
style={[styles.selectedbutton, { width: "50%" }]}
>
<Text style={styles.selectedbuttontext}>
{Config.immigerat[this.state.currentlySelectedItemIndex - 1].value}
</Text>
</TouchableOpacity>}
</View>
{currentlySelectedItemIndex !== 4 && (
<View
style={{
borderWidth: 1,
borderRadius: 3,
borderColor: "rgba(110,110,110,0.4)",
flex: 1,
marginHorizontal: 10,
marginTop: 30,
flexDirection: "row"
}}
>
<TouchableOpacity
activeOpacity={0.8}
onPress={() => {
this.extraOptionsRefresh()
//setTimeout(() => {
//this.extraOptionsRefresh();
//this.intialLoadValues();
//this.setState({ isItemChecked: !isItemChecked });
//}, 100);
}
}
style={{
// flex: 0.35,
alignItems: "center",
justifyContent: "center",
marginLeft: 15
}}
hitSlop={{ top: 20, bottom: 20, left: 50, right: 50 }}
>
<View
style={[
styles.button,
{
backgroundColor: "white",
borderColor: "rgba(110,110,110,0.4)",
borderWidth: 1,
borderRadius: 2,
width: 20,
height: 20
}
]}
>
{this.state.isItemChecked ? (
<Icon name={"check"} color={colors.LIGHT_BLUE} size={15} />
) : null}
</View>
</TouchableOpacity>
<Text
style={{
flex: 1,
marginVertical: 10,
marginLeft: 10,
fontFamily: "SourceSansPro-Bold",
color: "#242424",
fontSize: RFValue(12)
}}
>
{this.state.checkBoxData}
</Text>
</View>
)}
{(!this.state.isItemSelected && this.state.currentlySelectedItemIndex > 0) &&
<Animatable.View animation="fadeIn" duration={1200} style={{ flexGrow: 1, justifyContent: 'center', alignItems: 'center', flexDirection: 'row' }}>
<ResponsiveImage source={this.imageMap[this.state.currentlySelectedItemIndex]} initWidth="270" initHeight="220" />
</Animatable.View>
}
</View>
)}
<View>
<TouchableOpacity
testID='searchButton'
onPress={() => !disableButton && this.showAlert1()}
style={{
width: 130,
justifyContent: "center",
backgroundColor: colors.LIGHT_BLUE,
borderRadius: 100,
padding: 10,
alignSelf: "center",
marginTop: height > 700 ? 60 : 40,
marginBottom: 20
}}
>
<Text
style={{
textAlign: "center",
color: "#fff",
fontFamily: "SourceSansPro-Regular"
}}
>
Search
</Text>
</TouchableOpacity>
</View>
</Animatable.View>
</ScrollView>
);
SecondRoute = () => (
<ScrollView style={{ flex: 1, backgroundColor: "white" }}>
<View style={{ backgroundColor: "white" }}>
<View
style={{
alignSelf: "center",
justifyContent: "center",
width: width
}}
>
<View style={{ margin: 20, alignSelf: "center" }}>
<Text
style={{
textAlign: "center",
fontFamily: "SourceSansPro-Semibold",
color: "#2C393F",
fontSize: 15
}}
>
Select all countries you are keen to explore
</Text>
<Text
style={{
textAlign: "center",
color: "rgba(44, 57, 63,0.6)",
marginTop: 20,
fontFamily: "SourceSansPro-Semibold"
}}
>
From:
</Text>
<View style={styles.loginView}>
<Field
name="selectcountry"
placeholder={this.state.selectedval}
component={this.renderDropdown}
data={Config.countries}
/>
</View>
<Text
style={{
textAlign: "center",
color: "rgba(44, 57, 63,0.6)",
marginTop: 20,
fontFamily: "SourceSansPro-Semibold"
}}
>
To:
</Text>
</View>
</View>
<View>
<View style={styles.custombuttonView}>
<View style={{ width: "33%" }}>
<TouchableOpacity
testID={`${Config.intrestcountry[0].value + 'interestButton'}`}
onPress={() =>
this._countryIntrest(Config.intrestcountry[0].code)
}
>
<Image
style={styles.countryIcon}
source={this.state.countrybut1
? Images.usa_selected
: Images.usa_unavailable}
/>
</TouchableOpacity>
</View>
<View style={{ width: "33%" }}>
<TouchableOpacity
testID={`${Config.intrestcountry[1].value + 'interestButton'}`}
>
<Image
style={styles.countryIcon}
source={this.state.countrybut2
? Images.canada_selected
: Images.canada_unavailable}
/>
</TouchableOpacity>
</View>
<View style={{ width: "33%" }}>
<TouchableOpacity
testID={`${Config.intrestcountry[2].value + 'interestButton'}`}
onPress={() =>
this._countryIntrest(Config.intrestcountry[2].code)
}
>
<Image
</TouchableOpacity>
</View>
</View>
<View style={styles.custombuttonView}>
<View style={{ width: "33%" }}>
<TouchableOpacity
testID={`${Config.intrestcountry[3].value + 'interestButton'}`}
onPress={() =>
this._countryIntrest(Config.intrestcountry[3].code)
}
>
<Image
/>
</TouchableOpacity>
</View>
<View style={{ width: "33%" }}>
<TouchableOpacity
testID={`${Config.intrestcountry[4].value + 'interestButton'}`}
onPress={() =>
this._countryIntrest(Config.intrestcountry[4].code)
}
>
<Image
</TouchableOpacity>
</View>
<View style={{ width: "33%" }}>
<TouchableOpacity
testID={`${Config.intrestcountry[5].value + 'interestButton'}`}
onPress={() =>
this._countryIntrest(Config.intrestcountry[5].code)
}
>
<Image
/>
</TouchableOpacity>
</View>
</View>
</View>
<View>
<TouchableOpacity
testID='countrySearchButton'
onPress={() => !disableButton && this.showAlert1()}
style={{
}}
>
<Text
>
Search
</Text>
</TouchableOpacity>
</View>
</View>
</ScrollView>
);
}
_countryIntrest(code) {
// alert(code);
var index = countryIntrest.indexOf(code);
var butstr = "countrybut" + code;
if (index == -1) {
countryIntrest.push(code);
countryIntrestNow.push(code);
this.setState({ [butstr]: true });
this.intialLoadValues();
} else {
countryIntrest.splice(index, 1);
countryIntrestNow.splice(index, 1);
this.setState({ [butstr]: false });
this.intialLoadValues();
}
}
_immigreateIntrest = async(code) => {
if(code === 4){
)
return;
}
const { isItemSelected } = this.state;
if (code === "null") {
);
} else {
await this.setState(
);
}
}
renderScene = ({ route }) => {
switch (route.key) {
case 'first':
case 'second':
default:
return null;
}
};
render() {
return (
<View style={{ flex: 1 }}>
{this.props.isLoading && (
<View
style={{
}}
>
<Loader />
</View>
)}
<TabView
removeClippedSubviews={Platform.OS === "android" ? true : false}
style={{
backgroundColor: this.state.index === 0 ? "#DBDDDF" : "white"
}}
navigationState={this.state}
removeClippedSubviews={Platform.OS === "android" ? true : false}
renderTabBar={props => (
<TabBar
}}
pass
getLabelText={({ route }) => route.title}
/>
)}
/>
<UserinfoPopUp
visible={this.state.userInfoPopUpVisible}
onClose={()=>this.setState({ userInfoPopUpVisible: false })}
userPopUpSubmit={this._userPopUpSubmit.bind(this)}
/>
</View>
);
}
}
mapStateToProps = state => ({
userPressedGo: state.pathReducer.getImmipathDetails.userPressedGo,
});
mapDispatchToProps = dispatch => ({
dispatch
});
export default compose(
connect(
mapStateToProps,
mapDispatchToProps
),
reduxForm({
form: "pathexplorertab"
// validate
})
)(copilot({
tooltipComponent: TooltipComponent,
stepNumberComponent: StepNumberComponent
})(PathexploredTab));
Pathexplorer.js contains Pathexplorer class in which there is an component called ToolTipComponent from which i am calling an action but the action isn't reflected in mapStateToProps. The reason i am forced to do this is that i am using a library called react-native-copilot in which i have a custom tooltip component from which i want to access the state
Problem in this event:
onPress={store.dispatch(action)}
should be:
onPress={()=>store.dispatch(action)}
By the way you can connect your functional component like class component:
export default connect(
mapStateToProps,
mapDispatchToProps
)
)(TooltipComponent)

Passing username and family name from google login

I've managed to set up Google login using 'expo-google-app-auth'.
This is my Login.js, which handles the login page and the google login details and logic:
import React, { Component } from 'react'
import {Text,
View,
StyleSheet,
Image,
Alert} from 'react-native'
import { TouchableOpacity } from 'react-native-gesture-handler';
import { Provider as PaperProvider,
Button,
Caption} from 'react-native-paper'
import { createStackNavigator } from '#react-navigation/stack'
import { NavigationContainer } from '#react-navigation/native';
import MyDrawer from '../navigation/Drawer'
import QR from './QR'
const Stack = createStackNavigator();
import * as Google from 'expo-google-app-auth';
const IOS_CLIENT_ID =
"your-ios-client-id";
const ANDROID_CLIENT_ID =
"my-android-id";
class Login extends Component {
signInWithGoogle = async () => {
try {
const result = await Google.logInAsync({
iosClientId: IOS_CLIENT_ID,
androidClientId: ANDROID_CLIENT_ID,
scopes: ["profile", "email"]
});
if (result.type === "success") {
console.log("LoginScreen.js.js 21 | ", result.user.givenName, result.user.familyName, result.user.email, result.user.photoUrl);
this.props.navigation.navigate("MyDrawer", {
username: result.user.givenName,
lastname: result.user.familyName,
email: result.user.email,
photoUrl: result.user.photoUrl
}); //after Google login redirect to MyDrawer
return result.accessToken;
} else {
return { cancelled: true };
}
} catch (e) {
console.log('LoginScreen.js.js 30 | Error with login', e);
return { error: true };
}
};
render(){
return (
<PaperProvider>
<View style={styles.container}>
<View style={styles.imageCon}>
<Image
source={require('../img/logo-krug.png')}></Image>
</View>
<View style={styles.textCon}>
<Text style={styles.text}> Dobrodošli u eSTUDENT mobilnu aplikaciju!</Text>
</View>
<View style={styles.buttonCon}>
<Button
icon='camera'
mode='outlined'
onPress={this.signInWithGoogle}
>
google
</Button>
</View>
</View>
</PaperProvider>
)
}
}
export default function LoginStack() {
return (
<NavigationContainer>
<Stack.Navigator
initialRouteName='Login'
screenOptions={{
headerShown: false
}}>
<Stack.Screen name='MyDrawer' component={MyDrawer} />
<Stack.Screen name='Login' component={Login} />
</Stack.Navigator>
</NavigationContainer>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ecf0f1'
},
imageCon: {
height: '35%',
width: '100%',
justifyContent: "center",
alignItems: "center"
},
textCon:{
height:'20%',
alignItems: 'center',
justifyContent: 'center'
},
text: {
textAlign: "center",
fontSize: 20,
fontWeight: 'bold'
},
buttonCon:{
height: '30%',
justifyContent:'center',
alignItems: 'center'
},
});
And I want to pass the username, family name, email and profile picture to these 2 files.
Drawer.js, which handles the side Drawer and navigation:
import React from 'react'
import { createDrawerNavigator } from '#react-navigation/drawer';
import { NavigationContainer } from '#react-navigation/native';
import { Ionicons, MaterialIcons, Feather } from '#expo/vector-icons';
import { ScrollView,
TouchableOpacity,
Text,
View,
Image,
StatusBar,
StyleSheet,
} from 'react-native'
import QR from '../screens/QR';
import Odabir from '../screens/Odabir'
import { SafeAreaView } from 'react-navigation';
import { Divider } from 'react-native-paper'
const Drawer = createDrawerNavigator();
function CustomDrawerContent(props) {
return(
<SafeAreaView style={{flex:1}}>
<View style={{height: 150, alignItems: 'center', justifyContent: 'center', marginTop: Platform.OS === 'ios' ? 0 : StatusBar.currentHeight}}>
<Image source={require('../img/account.png')}
style={{height: 120, width: 120, borderRadius: 60}}
/>
</View>
<View style={{height: 50, alignItems:'center'}}>
<Text style={styles.naslov}> This is where I want to pass the username and last name </Text>
</View>
<Divider />
<ScrollView style={{marginLeft: 5,}}>
<TouchableOpacity
style={{marginTop: 20, marginLeft: 20}}
onPress={() => props.navigation.navigate('QR')}
>
<View style={{padding:10}}>
<Ionicons name='ios-qr-scanner' size={20} styles={{}}>
<Text style={styles.naslov}> QR</Text>
</Ionicons>
</View>
</TouchableOpacity>
<TouchableOpacity
style={{marginTop: 20, marginLeft: 20}}
onPress={() => props.navigation.navigate('Odabir')}
>
<View style={{padding:10}}>
<Ionicons name='ios-qr-scanner' size={20} styles={{}}>
<Text style={styles.naslov}> Odabir</Text>
</Ionicons>
</View>
</TouchableOpacity>
<TouchableOpacity
style={{marginTop: 20, marginLeft: 20}}
onPress={() => props.navigation.navigate('Odabir')}
>
<View style={{padding:10}}>
<Ionicons name='ios-qr-scanner' size={20} styles={{}}>
<Text style={styles.naslov}> Odabir</Text>
</Ionicons>
</View>
</TouchableOpacity>
</ScrollView>
</SafeAreaView>
)
}
export default function MyDrawer() {
return (
<NavigationContainer independent={true}>
<Drawer.Navigator initialRouteName='QR' drawerContent={props => CustomDrawerContent(props)}>
<Drawer.Screen
name="QR"
component={QR}
/>
<Drawer.Screen
name="Odabir"
component={Odabir}
/>
</Drawer.Navigator>
</NavigationContainer>
);
}
const styles = StyleSheet.create({
naslov: {
fontSize: 20,
},
})
and finally QR.js, which holds some basic information and I'd like to personalize it a bit since it's the 'Home' page users land on
import React, { Component } from 'react'
import {Text,
SafeAreaView,
View,
StyleSheet,
Image
} from 'react-native'
import Header from '../navigation/Header'
export default function QR({navigation}) {
return (
<SafeAreaView style={styles.container}>
<Header title='Moj QR' isHome={true} navigation={navigation}/>
<View style={styles.qrCon}>
<Image
style={styles.qr}
source={require('../img/QR_code_for_mobile_English_Wikipedia.svg.png')}
/>
</View>
<View style={styles.textCon}>
<Text style={styles.text}>This is where I want to pass the username and last name</Text>
<Text style={styles.text}>Ovo je tvoj QR kod</Text>
</View>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ecf0f1',
alignItems: 'center',
},
qrCon:{
width: '60%',
height: '60%',
alignItems: 'center',
justifyContent: 'center',
},
qr: {
width: '120%',
height: '120%',
resizeMode: 'contain'
},
textCon: {
height: '7%'
},
text:{
fontSize: 35,
fontWeight: '600'
},
buttonCon:{
height: '15%',
justifyContent:'center',
alignItems: 'center'
}
})
The example I'm following used {this.props.navigation.getParam("username")} but that isn't working for me. How would I exactly pass the data?
I had this issue recently. React navigation 5 doesn't support props.navigation.getParam instead you can use this.props.route.params to access the data you passed in your navigation prop. So to access the username you can use this.props.route.params.username;
The way to solve this, at least passing data to the Drawer.js component is to rewrite the code like this:
if (result.type === "success") {
console.log("LoginScreen.js.js 21 | ", result.user.givenName, result.user.familyName, result.user.email, result.user.photoUrl);
this.props.navigation.navigate("MyDrawer",
username = result.user.givenName,
lastname = result.user.familyName,
email = result.user.email,
photoUrl = result.user.photoUrl);
return result.accessToken;
;
Then just putting that as a variable in Drawer.js
<View style={{height: 30, alignItems:'center'}}>
<Text style={styles.naslov}>{username} {lastname}</Text>
</View>

react native how to pass this.state to tabBarComponent

I customize TabBarCompenet and trying to pass cart value so that could keep updated cart on value change. But app throws error
Undefined is not an object '_this.state.cartAmount'
App.js
var {height, width} = Dimensions.get('window');
const DashboardTabNavigator = createBottomTabNavigator({
Tab1: {screen: FoodCategoryStack},
Tab2: {screen: EventsStack}
},
{
tabBarComponent:({ props }) => (
<AddTabButton {...props} cartAmount={this.state.cartAmount} />
)});
const DashboardStackNavigator = createStackNavigator({
DashboardTabNavigator: DashboardTabNavigator
},
{
defaultNavigationOptions: ({ navigation }) => {
return {
header: null,
headerLeft: <MaterialIcons
onPress={() => navigation.openDrawer()}
style={{ paddingLeft: 10 }}
name="menu"
size={30}
/>
};
}
}
);
const CustomDrawerComponent = (props) => (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ height: 150, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center', marginTop: 20 }}>
</View>
<ScrollView>
<DrawerItems {...props} />
</ScrollView>
</SafeAreaView>
)
const AppDrawerNavigator = createDrawerNavigator({
Home: {
screen: DashboardStackNavigator,
},
Events: {
screen: EventScreen
}
},
{
contentComponent: CustomDrawerComponent,
drawerWidth: width * 0.85
});
const AppSwitchNavigator = createSwitchNavigator({
Welcome: { screen: splashScreen },
Dashboard: { screen: AppDrawerNavigator }
});
const AppContainer = createAppContainer(AppSwitchNavigator);
export default class App extends React.Component {
constructor(props){
super(props)
this.state = {
cartAmount: '18.50'
}
}
componentWillMount() {
console.log('componentWillMount Tab View')
}
componentDidMount() {
console.log('componentDidMount Tab View')
console.log(this.state.cartAmount)
}
HandleTabPressOne () {
console.log('Cart function called')
this.setState({ cartAmount: '12.20' });
alert(this.state.cartAmount)
}
render() {
return ( <AppContainer{...this.props} />);
}
}
AddTabButton.js
import React, {Component} from 'react';
import {StyleSheet, Animated, Text, TouchableOpacity, View, Dimensions} from "react-native";
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
var {height, width} = Dimensions.get('window');
const AddTabButton = (props) => {
return (
<View style={{flex: 0.1, backgroundColor: '#FF0000', borderColor: '#FF0000', borderWidth: 1}}>
<View style={{flexDirection:'row', justifyContent: 'space-around', alignItems: 'center', paddingTop: 5}}>
<TouchableOpacity onPress={() => navigation.navigate('Tab1')} style={{alignItems: 'center', marginLeft: 5}}>
<MaterialIcons name="local-pizza" size={24} color="#FFFFFF" />
<Text style={styles.textFAB}>Menu</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.HandleTabPressOne}style={{alignItems: 'center'}}>
<MaterialIcons name="event-available" size={24} color="#FFFFFF" />
<Text style={styles.textFAB}>Event</Text>
</TouchableOpacity>
<View style={styles.cartFAB}>
<MaterialIcons name="shopping-basket" size={24} color="#FFFFFF" style={{marginTop: 10}} />
<Text style={styles.totalCart}>$ {(this.props.cartAmount != null) ? this.props.cartAmount : '12.55'}</Text>
</View>
</View>
</View>
);
};
export default AddTabButton;
As per suggestion of Andrew I implemented redux to overcome the scenario.

Resources