This information may be useful to someone.
In my scenario, if a user receives a notification but hasn't logged in, then the app should not redirect them to the desired screen.
If the user is not on the Login screen, and user press the notification, we should redirect them (Screen2 in my case).
For this I send the navigation reference to my NotificationHelper
Using:
@react-navigation/native: 6.X
@react-native-firebase/messaging: 17.x
@notifee/react-native: 7.x
Code:
MainScreen.tsx
import { createNavigationContainerRef } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
const MainScreen: React.FC = () => {
const Stack = createNativeStackNavigator();
const navigationRef = createNavigationContainerRef();
return (
<NavigationContainer ref={navigationRef}>
<Stack.Navigator screenOptions={{ headerShown: false }}>
<Stack.Screen name="Login" component={LoginScree} />
<Stack.Screen name="Screen1" component={Screen1} />
<Stack.Screen
name="Screen2"
component={Screen2}
/>
</Stack.Navigator>
<NotificationHelper navigationRef={navigationRef} />
</NavigationContainer>
);
};
NotificationHelper.tsx
import messaging, {
FirebaseMessagingTypes,
} from '@react-native-firebase/messaging';
import { NavigationContainerRefWithCurrent } from '@react-navigation/native';
import { FC, useCallback, useEffect } from 'react';
type PropsType = {
navigationRef: NavigationContainerRefWithCurrent<ReactNavigation.RootParamList>;
};
const NotificationHelper: FC<PropsType> = (props: PropsType) => {
const redirectToScreen = useCallback(
(notification: any) => {
if (props.navigationRef) {
const currentRoute = props.navigationRef.getCurrentRoute()?.name;
if (currentRoute) {
if (currentRoute !== 'Login') {
props.navigationRef.navigate('Screen2', {
param1: notification.property1,
param2: notification.property2,
});
}
}
}
},
[props.navigationRef],
);
useEffect(() => {
const unsubscribeOpenedApp = messaging().onNotificationOpenedApp(
async (remoteMessage) => {
if (remoteMessage.data) {
console.debug('User pressed notification');
redirectToScreen(remoteMessage.data);
}
},
);
const unsubscribeForegroundOpenApp = notifee.onForegroundEvent(
({ type, detail }) => {
switch (type) {
case EventType.PRESS:
console.debug('User pressed notification');
if (detail.notification && detail.notification.data) {
redirectToScreen(
detail.notification.data,
);
}
break;
}
},
);
return () => {
unsubscribeOpenedApp();
unsubscribeForegroundOpenApp();
};
}, [redirectToScreen]);
return null;
};
export default NotificationHelper;