Marco Disco
Marco Disco

Reputation: 565

React Native Navigation 5.x gives navigation error

I switched months ago to @react-navigation/native v5.x that I thought I knew pretty well. But I get an error if I want to move between screens:

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

Navigatior.js

import React from 'react';

import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import {createMaterialBottomTabNavigator} from '@react-navigation/material-bottom-tabs';

import AddBook from '../screens/AddBook';
import BookArchive from '../screens/BookArchive';
import SearchResults from '../screens/SearchResults';

const Stack = createStackNavigator();

const Navigator = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Add" component={AddBook} />
        <Stack.Screen name="Results" component={SearchResults} />
        <Stack.Screen name="Archive" component={BookArchive} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

export default Navigator;

AddBook.js

.. // CODE

import {useNavigation} from '@react-navigation/native';

const AddBook = ({data, loading}) => {
  const navigation = useNavigation();

..// CODE

<Button
title="Search"
style={styles.button}
onPress={() => navigation.navigate('Results')}
/>

From the official docs:

If we call navigation.navigate with a route name that we haven't defined on a stack navigator, nothing will happen. Said another way, we can only navigate to routes that have been defined on our stack navigator — we cannot navigate to an arbitrary component.

My page is listed correctly (pretty simple), so why it doesn't work and I get the error?

Thanks

Upvotes: 1

Views: 2190

Answers (3)

Slycreator
Slycreator

Reputation: 1230

I recently faced this issue with version 6 and was able to resolve it by changing from core to native. below is the sample code.

import { StackActions, useNavigation} from '@react-navigation/core' //from this
import { StackActions, useNavigation} from '@react-navigation/native' // to this

Upvotes: 1

Marco Disco
Marco Disco

Reputation: 565

I didn't get what happened but I have to create another app and move everything there, and works! Maybe some installations went wrong...

Upvotes: 1

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Try this way

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button
        onPress={() => navigation.navigate('moveScreenName')}
        title="Go to moveScreenName"
      />
    </View>
  );
}

Upvotes: 0

Related Questions