React Native Navigate to Particular Screen When Notification is Clicked

I am trying to implement navigation upon the user click on a notification that they have received. I am successfully receiving the notifications with expo-notifications and accept data (routes) from API but unable to navigate to another screen when user clicks on a notification.

useNotifications:

export default useNotifications = () => {
    ...

    useEffect(() => {
        registerForPushNotificationsAsync().then((token) => {
            setExpoPushToken(token);
            alert(token);
        });

        notificationListener.current = Notifications.addNotificationReceivedListener(
            (notification) => {
                setNotification(notification);
                console.log(notification);
            }
        );

        responseListener.current = Notifications.addNotificationResponseReceivedListener(
            (response) => {
                //notification is received OK
                console.log("opened");
                
                //here I want to navigate to another screen using rootnavigation
                navigation.navigate("Account"); 

                //alert shows fine
                alert("ok");
            }
        );

        return () => {
            Notifications.removeNotificationSubscription(notificationListener);
            Notifications.removeNotificationSubscription(responseListener);
        };
    }, []);
};

Navigator:

const SettingsNavigation = ({ component }) => {
    useNotifications();

    return (
        <Stack.Navigator mode="card" screenOptions={{ headerShown: false }}>
            <Stack.Screen
                name="Main"
                component={component}
                options={{ title: "Home" }}
            />

            <Stack.Screen
                name="Timetable"
                component={TimetableScreenBoss}
                options={menuOptions("Schedule")}
            />

            <Stack.Screen
                name="Account"
                component={AccountNavigator}
                options={menuOptions("Account", false)}
            />
        </Stack.Navigator>
    );
};

root navigation:

mport React from "react";

export const navigationRef = React.createRef();

const navigate = (name, params) =>
    navigationRef.current?.navigate(name, params);

export default {
    navigate,
};

app.js:

import { navigationRef } from "./app/navigation/rootNavigation"; //rootnavigation

<NavigationContainer navigationRef={navigationRef}>
    <CustomNavigator>   
</NavigationContainer>
1 Like

I had a dumb mistake.

Instead of

navigationRef={navigationRef}

should be

ref={navigationRef}

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.