I'm using react-navigation
and react-native-push-notification
. How can I open a certain StackNavigator's
screen in onNotification
callback? Should work when:
I only need it working in Android for now.
I've tried to pass a callback function to notification in my component:
_handleClick() {
PushNotification.localNotification({
foreground: false
userInteraction: false
message: 'My Notification Message'
onOpen: () => { this.props.navigation.navigate("OtherScreen") },
})
}
And to fire onOpen
in PushNotification
config:
onNotification: function(notification) {
notification.onOpen()
}
But it seems that functions can't be passed to notification, unless a value is a string it's ignored, causing onOpen
to be undefined.
First, we import the react-native-notifications library in App. js . In the constructor, we call registerRemoteNotifications() , which will show the permission dialog on iOS and register the app on FCM on Android.
push : pushes a new instance of the screen even if it already exists in the current stack. navigate : if the component with its name exists in the current stack, then it goes to that screen. If not, it creates a new instance of the screen and pushes it onto the stack.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With