Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - How to open route from push notification

Tags:

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.

like image 704
Jacka Avatar asked Nov 15 '17 13:11

Jacka


People also ask

How do I open notifications in React Native?

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.

What is difference between push and navigate in React Native?

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.


1 Answers

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
  }

}
like image 61
Jacka Avatar answered Oct 18 '22 07:10

Jacka