Search code examples
javascriptreact-nativeundefinedreact-navigationstack-navigator

Stack Navigator in React Native. Error "undefined is not an object (evaluating this.props.navigation)"


It's taking me forever to figure out the obvious, would appreciate some help.

Im using a stack navigator, when a button is pressed it will simply go to another page.

In app.js I created a stack navigator:

const Switcher = createStackNavigator(
  {
    TaskPg: ListScreen,
    AboutPg: AboutScreen
  },
  {
    initialRouteName: "TaskPg",
    defaultNavigationOptions: {
      title: 'BlueList'
    }
  }
)

In the ListScreen there is a button the user can press to go to the about page.

const ListScreen = () => {


    return (
        <View style={styles.container}>

            {/* add task component with date picker */}
            <AddItemModel />

            {/* button pressed to goto About Screen */}
            <Button
                onPress={() => this.props.navigation.navigate(AboutScreen)}
                title="About App" />

            {/* sign out button linked to firebase log out */}
            <TouchableOpacity onPress={() => firebase.auth().signOut()} >
                <Text style={styles.button} >Sign Out</Text>
            </TouchableOpacity>

        </View>
    );

}

export default ListScreen

Run code and every time I press the button I get the error undefined is not an object (evaluating this.props.navigation)


Solution

  • Since your ListScreen is a functional component, this.props doesn't exist.

    Change your ListScreen declaration to:

    const ListScreen = props => {...}
    

    and access your navigation object like this:

    props.navigation.navigate(AboutScreen);