reactjsreact-nativepush-notificationreact-native-push-notification

How to add click action for push notification in React native


I want to navigate to particular app screen after click on remote push notification. How can i implement this with react native. I am using react-native-push-notification library


Solution

  • react-native-push-notification has an on notification press handler -> onNotification which is called every time the user presses or has received a notification (this is from the react-native-push-notification documentation). In an application you create a NavigationService component which uses the top level navigator reference set in your App.js file. With this navigator, in the onNotification callback you can then navigate to any screen in your application and use the notification data you have received for your purposes, which can be passed to the navigating screen through the navigator (in its state). Some psuedo code can look like this:

    NotificationService.js:

    import NavigationService from './NavigationService';
    import PushNotification from "react-native-push-notification";
    
    PushNotification.configure({
        onNotification: function(notification) {
            const { data } = notification;
    
            NavigationService.navigate('Screen', { notificationData: data });
        }
    });
    

    NavigationService.js:

    import { NavigationActions } from 'react-navigation';
    
    let _navigator;
    
    function setTopLevelNavigator(navigatorRef) {
        _navigator = navigatorRef;
    }
    
    function navigate(routeName, params) {
        _navigator.dispatch(
            NavigationActions.navigate({
                routeName,
                params,
            })
        );
    }
    

    Edit: Also you have to create an AppContainer, (This is placed in your App.js)

     import { createSwitchNavigator } from 'react-navigation';
     import { createAppContainer } from 'react-navigation';
    
     const AppContainer = createAppContainer(createSwitchNavigator({...Screens}));
    
     export default class App extends React.Component {
         ...
         render() {
              return (
                   <View>
                        <AppContainer ref={ (navigatorRef) => { NavigationService.setTopLevelNavigator(navigatorRef); } } />
                   </View>
              )
    
         }
     }