Home > Enterprise >  TypeError: undefined is not an object (evaluating 'props.navigation.navigate')
TypeError: undefined is not an object (evaluating 'props.navigation.navigate')

Time:09-28

I'm using react-navigator 4.x and I have only one page to navigate But when I click <Button onPress={() => {props.navigation.navigate({ routeName: 'Login' })}} title="Go To" /> in photos page, I got this error:

import React, { useEffect, useRef } from 'react';
import { View, Button, Text, StyleSheet, TouchableOpacity } from 'react-native';
import 'react-native-gesture-handler';


const NextButton = props => {

    return (

        <View>
            <Button onPress={() => {
                props.navigation.navigate({ routeName: 'Login' })
            }} title="Go To" />
        </View>
    );
}
export default NextButton;


import { createStackNavigator } from "react-navigation-stack";
import { createAppContainer } from "react-navigation";
import Onboarding from "../components/Onboarding";
import Login from './../screens/Login';

const AppNavigator = createStackNavigator({
    Intro: Onboarding,
    Login: Login,
});

export default createAppContainer(AppNavigator);

CodePudding user response:

Your NextButton is not really a part of your navigation stack, and hence props.navigation will be undefined, unless you are passing it as prop from your screen, thus the error TypeError: undefined is not an object (evaluating 'props.navigation.navigate').

To get navigation inside your NextButton component, you can either pass it as a prop from the screen you are rendering your NextButton. Or since you are using an older version of the library, you can wrap your NextButton with the withNavigation HOC to get access to navigation props.

import { withNavigation } from 'react-navigation';

const NextButton = props => {
  return (
    <View>
      <Button 
        onPress={() => {
          props.navigation.navigate({ routeName: 'Login' })
        }} 
        title="Go To" 
      />
    </View>
  );
}
export default withNavigation(NextButton);

CodePudding user response:

Use NavigationContainer instead of createAppContainer, I think that changed from v4 to v5.

import { NavigationContainer } from '@react-navigation/native';
  • Related