Home > OS >  Undefined is not an object (evaluating 'navigation.navigate') when trying to navigate betw
Undefined is not an object (evaluating 'navigation.navigate') when trying to navigate betw

Time:05-19

I try to navigate between two pages in a React Native app. I keep getting errors for my implementations but I don't know why.

I have the following setup for a "Home" and "Settings" site in the React Native app with Navigator adjusted from the documentation:

App.js

import Home from "./Home";
import { NavigationContainer } from '@react-navigation/native';

export default function App() {
  return <NavigationContainer><Home/></NavigationContainer>
}

Home.jsx

const Home = ({ navigation }) => {
  return (
    <View style={["some style...", {}]}>
      <View style={["some style..."]}>
        <TouchableOpacity onPress={() =>
        navigation.navigate('Settings')}>
          <Image "some image..."/>
        </TouchableOpacity>
      </View>
    </View>

Settings.jsx

A component which should be rendered.

MyStack.jsx

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import Home from './Home';
import Settings from './Settings';

const Stack = createNativeStackNavigator();

const MyStack = () => {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Home"
          component={Home}
        />
        <Stack.Screen name="Settings" component={Settings} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

I get undefined is not an object (evaluating 'navigation.navigate'). Also adding this.props to navigation.navigate('Settings') throws and error. I am just not able to access my Navigator.

CodePudding user response:

You seem to be setting up a navigator, but never using it, since in App.js you are just calling <Home/>.

  1. Change App.js to the code below.

use the correct path for the import

import MyStack from "./MyStack";

export default function App() {
  return <MyStack/>
}
  1. Add at the end of MyStack.jsx:
export default MyStack;
  • Related