React Native - How to open route from push notification
Okay, it seems like I gotta post my own solution :)
// src/services/push-notification.js
const PushNotification = require('react-native-push-notification')
export function setupPushNotification(handleNotification) {
PushNotification.configure({
onNotification: function(notification) {
handleNotification(notification)
},
popInitialNotification: true,
requestPermissions: true,
})
return PushNotification
}
// Some notification-scheduling component
import {setupPushNotification} from "src/services/push-notification"
class SomeComponent extends PureComponent {
componentDidMount() {
this.pushNotification = setupPushNotification(this._handleNotificationOpen)
}
_handleNotificationOpen = () => {
const {navigate} = this.props.navigation
navigate("SomeOtherScreen")
}
_handlePress = () => {
this.pushNotification.localNotificationSchedule({
message: 'Some message',
date: new Date(Date.now() + (10 * 1000)), // to schedule it in 10 secs in my case
})
}
render() {
// use _handlePress function somewhere to schedule notification
}
}
This solution I found over the official website of Firebase and this seems to be the best example/sample work for this. Below is the sample snippet and also the link attached. Hope it help others.
import React, { useState, useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
import { NavigationContainer, useNavigation } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
function App() {
const navigation = useNavigation();
const [loading, setLoading] = useState(true);
const [initialRoute, setInitialRoute] = useState('Home');
useEffect(() => {
// Assume a message-notification contains a "type" property in the data payload of the screen to open
messaging().onNotificationOpenedApp(remoteMessage => {
console.log(
'Notification caused app to open from background state:',
remoteMessage.notification,
);
navigation.navigate(remoteMessage.data.type);
});
// Check whether an initial notification is available
messaging()
.getInitialNotification()
.then(remoteMessage => {
if (remoteMessage) {
console.log(
'Notification caused app to open from quit state:',
remoteMessage.notification,
);
setInitialRoute(remoteMessage.data.type); // e.g. "Settings"
}
setLoading(false);
});
}, []);
if (loading) {
return null;
}
return (
<NavigationContainer>
<Stack.Navigator initialRouteName={initialRoute}>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Settings" component={SettingsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
Link: https://rnfirebase.io/messaging/notifications#handling-interaction