How to navigate screen on notification open in React Native with One Signal?
You can dispatch a NavigationAction
or perform a navigate
action when onOpened
is fired. Following snippet should work:
componentWillMount() {
OneSignal.inFocusDisplaying(0);
OneSignal.removeEventListener('opened', this.onOpened.bind(this));
OneSignal.addEventListener('opened', this.onOpened.bind(this));
}
onOpened(openResult) {
let data = openResult.notification.payload.additionalData;
// ScreenName is the name of the screen you defined in StackNavigator
this.props.navigation.navigate('ScreenName', data)
}
To achieve the desired behavior you can do couple of things. You can manually check the notification and state of the router and if its necessary redirect the user to the screen or you can use the Deep Linking functionality.
To use Deep Linking you attach url
parameter to your notification while sending it. To direct user to the correct screen in your app you can use react-navigation deep linking functionality.
From One Signal Documentation
url
string The URL to open in the browser when a user clicks on the notification. Example: http://www.google.comNote: iOS needs https or updated NSAppTransportSecurity in plist
From React Navigation Documentation
Deep Linking
In this guide we will set up our app to handle external URIs. Let's start with the
SimpleApp
that we created in the getting started guide. In this example, we want a URI likemychat://chat/Taylor
to open our app and link straight into Taylor's chat page.
In search for the solution I landed on this question and I think most of the answers are now old. So, in case anyone looking for the solution can try this.
OneSignal.setNotificationOpenedHandler((notificationResponse) => {
const { notification } = notificationResponse;
if (notification) {
const { additionalData = null } = notification;
if (additionalData) {
const { type } = additionalData;
navigateToScreen(type);
}
}
});
const navigateToScreen = (type) => {
switch (type) {
case "post":
case "track":
navigation.navigate("SinglePost");
return;
default:
return;
}
};