Couldn't find a navigation object. Is your component inside a screen in a navigator?

Viewed 30100

In My below code when I use useNavigation() then it gives an error like my quiestion How to use useNavigation, Please any one can solve this error... ERROR:Couldn't find a navigation object. Is your component inside a screen in a navigator? I followed code from here https://rnfirebase.io/messaging/notifications#handling-interaction

import React, {useState, useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
import { NavigationContainer, useNavigation } from "@react-navigation/native";
import { createStackNavigator, HeaderTitle, } from "@react-navigation/stack";
const Stack = createStackNavigator();

function App(props) {
     const navigation = props.navigation
    //const navigation = useNavigation();
    const [initialRoute, setInitialRoute] = useState('Splash Screen');

    useEffect(() => {
        messaging().onMessage(remoteMessage => {
            navigation.navigate("Description Screen");
            console.log(props.navigation)
        });
    }, []);

    return (
        <NavigationContainer>
            <Stack.Navigator
                initialRouteName={initialRoute}
                headerMode="none"
                screenOptions={{
                    gestureEnabled: true,

                }}
            >

                <Stack.Screen name="Splash Screen" component={SplashScreen} />
                <Stack.Screen name="Description Screen" component={DescriptionScreen} />
            </Stack.Navigator>

        </NavigationContainer>

    );
}

export default App;
1 Answers

You can't access navigation because it's not ready yet. you can create Ref for your navigation then export it and use it where you want.

// App.js

import { NavigationContainer } from '@react-navigation/native';
import { navigationRef } from './RootNavigation';

export default function App() {
  return (
    <NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>
  );
}

`

Then you can use it by defining and exporting your method

// RootNavigation.js

import * as React from 'react';

export const navigationRef = React.createRef();

export function navigate(name, params) {
  navigationRef.current?.navigate(name, params);
}

any way you can use onReadycall back to say that your navigation is ready

// App.js

import { NavigationContainer } from '@react-navigation/native';
import { navigationRef, isReadyRef } from './RootNavigation';

export default function App() {
  React.useEffect(() => {
    return () => {
      isReadyRef.current = false
    };
  }, []);

  return (
    <NavigationContainer
      ref={navigationRef}
      onReady={() => {
        isReadyRef.current = true;
      }}
    >
      {/* ... */}
    </NavigationContainer>
  );
}

Related