links: React Native MOC
Sometimes you might want to navigate the user to some screen inside your app when they click on the notification.
For example, when you receive a message from WhatsApp and you click on the notification it opens the app and redirects the user to the specific chat that’s related to the notification rather than keeping the user on the home screen.
Deep Linking allows push notifications to send the users directly to specific pages within an app making it easy for users to reconsider an abandoned cart, view new content, shop a sale, or fall in love with new features.
React Navigation library provides deep linking but the initial configuration will take more effort and introducing it in the brownfield app will consume a significant amount of time.
The following guide is kind of a hack, the better solution is to add deep linking
JS handling
- Create a notification listener when the app starts
- There are three scenarios for notifications
- App is in a closed state and it’s opened from a notification
- App is in Foreground
- App is in Background
- Whenever the listener receives a notification payload save it as a pending action
- While setting the pending action, check if navigation is ready
- if navigation is ready handle the pending route action
- if navigation is not ready call the goToPendingRoute in your Splash Screen which indicates that navigation is ready
Meta Code for this is as follows
export const notificationClickListener = () => {
FirebaseOrMoEngage.setEventListener('pushClicked', (notificationPayload) => {
const {module} = notificationPayload?.data?.payload;
const {screen, params} = notificationPayload?.data?.payload;
setPendingRoute(module, {
screen,
params,
});
});
};export function goToPendingRoute() {
if (pendingRoute?.routeName && pendingRoute?.params) {
navigate(pendingRoute.routeName, {...pendingRoute.params});
pendingRoute.routeName = '';
pendingRoute.params = undefined;
}
}
export function setPendingRoute(route: string = '', params: object = {}) {
pendingRoute.routeName = route;
pendingRoute.params = params;
if (navigationRef?.isReady()) {
goToPendingRoute();
}
}tags: react-native notifications