I'm trying to set some conditions on the React Navigation headers (for example, if the cart contains items and you want to go back to the home screen, display an alert, and empty cart). The cart is managed in Redux.
How do I get the "currentRouteName" constant to use it as a conditional in "DrawerStack" for example?
I try to use redux to store this value, but it crashes the app.
Also, I don't know why but also the tracking event for amplitude is crashing my app too.
Thanks for the help!
The structure of my screens goes as follows:
<NavigationContainer
ref={navigationRef}
onReady={() => {
SplashScreen.hideAsync();
routeNameRef.current = navigationRef.current.getCurrentRoute().name;
}}
onStateChange={() => {
const previousRouteName = routeNameRef.current;
const currentRouteName = navigationRef.current.getCurrentRoute().name;
if (previousRouteName !== currentRouteName) {
routeNameRef.current = currentRouteName;
trackAmplitudeEvent("Route",
{
name: currentRouteName,
...restaurantProfileId && {restaurantProfileId}
})
}
}}
>
--------------
<Drawer.Navigator
drawerContent={props => <CustomDrawer {...props} />}
screenOptions={{
drawerPosition: "right",
drawerActiveTintColor: "#fff",
drawerInactiveTintColor: "#3D3D3D",
drawerActiveBackgroundColor: foodhiRed,
drawerLabelStyle: { fontSize: 16, marginLeft: -20 }
}}>
<Drawer.Screen
name="Home"
component={HomeStack}
options={{
drawerIcon: ({ color }) => <View><Ionicons name="home-outline" size={26} color={color} /></View>,
headerTitle: () => (
<Text
onPress={() => {
if (cartItems.length > 0) {
Alert.alert(
"Warenkorb wird geleert",
"Wenn du zum Hauptmenü zurückkehrst, wird der Warenkorb zurückgesetzt",
[
{
text: "Ja", onPress: () => {
dispatch(emptyCart());
navigation.popToTop();
},
style: "default"
},
{
text: "Abbrechen",
style: "cancel"
}
]
)
} else navigation.popToTop();
}}
style={{
fontSize: 24,
color: "#fff",
fontFamily: 'Rubik_600SemiBold',
}}>
Foodhi
</Text>
),
headerTintColor: "#fff",
headerShadowVisible: false,
headerStyle: {
backgroundColor: foodhiGreen,
},
headerLeft: () => {
if (screenName !== "StoresIndex") {
return (
<Pressable onPress={() => emptyCartAlert()}>
<Icon name="chevron-left" color="#fff" size={32} style={{ paddingLeft: 10 }} />
</Pressable>
)
}
},
headerRight: () => (
<TouchableOpacity style={{ marginRight: 20 }}
onPress={() => navigation.dispatch(DrawerActions.openDrawer())}>
<Icon name="menu" size={30} color="#fff" />
</TouchableOpacity>
),
}}
/>
</Drawer.Navigator >