Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native - How to navigate on Push notification click?

I am using react-native-push-notification. I had the issue of notifications not being displayed when the app is in background/killed state, to which the solution in multiple forums and GitHub is that we initialize and configure push notification (PushNotification.configure()) in index.js Inside the PushNotification.configure() function, onNotification() is the function called when the Push Notification is clicked. On click, I want to navigate to a particular screen in the app, but that is not possible currently as there is no navigation prop available in index.js

Is there any way the navigation could be made possible ?

like image 684
Fullmetal Avatar asked Oct 14 '25 09:10

Fullmetal


1 Answers

This is what you can do. Firstly, you can initialize and export navigationRef from the file in which you've NavigationContainer.

// App.js
    
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { navigationRef } from './RootNavigation';

export const navigationRef = React.createRef();

export function navigate(name, params) {
  navigationRef.current?.navigate(name, params);
}
    
export default function App() {
  return (
        <NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>
  );
}

then you can import it in which you've PushNotification.configure()

// notification-service.js

import PushNotification from 'react-native-push-notification';
import { navigationRef } from './App';

/* Your other code */

PushNotification.configure({
  onNotifications: (notification) => {
  
  // Now you'll have access to the navigation object's function here...

  }
})

You can get more clarity from the docs here: navigating-without-navigation-prop

like image 59
Owais ul wara Avatar answered Oct 17 '25 01:10

Owais ul wara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!