React Native - How to open route from push notification

Jacka picture Jacka · Nov 15, 2017 · Viewed 11.2k times · Source

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:

  • app is closed
  • app is in the foreground
  • app is in the background

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.

Answer

Jacka picture Jacka · Nov 22, 2017

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
  }

}