How to use navigation props inside App.js file in react native

Viewed 1968

i have made a react native application in which i implemented firebase notification. I have put all the notification related service code in app.js file. Here is my app.js file


export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    };
}



  componentWillUnmount() {
    this.notificationListener();
    this.notificationOpenedListener();
  }

  async createNotificationListeners() {
    /*
    * Triggered when a particular notification has been received in foreground
    * */
    this.notificationListener = firebase.notifications().onNotification((notification) => {
        const { title, body } = notification;
       // this.showAlert(title, body);
        ToastAndroid.show("Notfictatoin recieved......"+title+"..."+body,ToastAndroid.LONG)
    });

    /*
    * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
    * */
    this.notificationOpenedListener = firebase.notifications().onNotificationOpened((notificationOpen) => {



     const navigateAction = NavigationActions.navigate({
      routeName: 'OrderHistory',
      params: {},
  })

 this.props.navigation.dispatch(navigateAction)




    });

    /*
    * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
    * */
    const notificationOpen = await firebase.notifications().getInitialNotification();
    if (notificationOpen) {
       // const { title, body } = notificationOpen.notification;
        //this.showAlert(title, body);
        ToastAndroid.show("notification inintalss....",ToastAndroid.LONG)
    }
    /*
    * Triggered for data only payload in foreground
    * */
    this.messageListener = firebase.messaging().onMessage((message) => {
      //process data message
      // console.log(JSON.stringify(message));
      ToastAndroid.show(JSON.stringify(message),ToastAndroid.LONG)
      this.displayNotification(message)
    });
  }
  displayNotification = (notification) => {
      if (Platform.OS === 'android') {
          const localNotification = new firebase.notifications.Notification({
              sound: 'default',
              show_in_foreground: true,
          }).setNotificationId(notification._from)
          .setTitle(notification._data.title)
          .setSubtitle(notification.subtitle)
          .setBody(notification._data.content)
          .setData(notification.data)
              .android.setChannelId('notification_channel_name') // e.g. the id you chose above
              .android.setSmallIcon('logo') // create this icon in Android Studio
              .android.setColor('#D3D3D3') // you can set a color here
              .android.setPriority(firebase.notifications.Android.Priority.High);

          firebase.notifications()
              .displayNotification(localNotification)
              .catch(err => console.error(err));

      }
      else if (Platform.OS === 'ios') {
        console.log(notification);
        const localNotification = new firebase.notifications.Notification()
            .setNotificationId(notification._from)
            .setTitle(notification._data.title)
            .setSubtitle(notification.subtitle)
            .setBody(notification._data.content)
            .setData(notification.data)
            .ios.setBadge(notification.ios.badge);

        firebase.notifications()
            .displayNotification(localNotification)
            .catch(err => console.error(err));

    }
  }

  componentDidMount(){
    this.createNotificationListeners(); //add this line
  }




  render() {
    return (
      <AppNavigator/>
    );
  }
}

The AppNavigator file is seperate file which puts all the navigator like stacknavigator and drawernavigator for the whole app. Now on notifcation click when i want to go to the particular screen then is gives me error that this.props.navigatio.dispatch is undefined . How can i solve this problem? Thanks in advance.

3 Answers

Export App.js withNavigation() so that your navigator can pass the navigation prop to your App component. Import withNavigation in App.js, then remove export default at the beginning of the class, and then export default withNavigation at the end of the page after the last curly brace '}';

import { withNavigation } from 'react-navigation';

class App extends React.Component { ... }

export default withNavigation(App);

First you need to create RootNavigation.js file with the following content

import { NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

// add other navigation functions that you need and export them

export default {
  navigate,
  setTopLevelNavigator,
};

Then in your App.js you need to include that file as NavigationService and add as a ref parameter to your navigation. After that you will be available to use navigation call to your screen by using NavigationService.navigate('ChatScreen', { userName: 'Lucy' });

Example of App.js below

    ...
    import NavigationService from './src/AppNavigation/RootNavigation';
    
    ...
    
    class App extends React.Component {
    
    ...
    
      async componentDidMount() {
    
    
        // For example you are using on message notifications
        this.onMessageListener = messaging().onMessage(async remoteMessage => {
        ...
       
        NavigationService.navigate('ChatScreen', { remoteMessage: remoteMessage })
    
        ...
        });
    
    ...
    
    }
    
    ...
    
      render() {
    
        return (
              <AppNavigation
                ref={navigatorRef => {
                  NavigationService.setTopLevelNavigator(navigatorRef);
                }}>
              {/* ... */}
              </AppNavigation>
        )
      }
    
    }
    export default App
Related