React Navigation - cannot read property 'navigate' of undefined

20,906

If you rename navigate={this.props.navigator} to navigator={this.props.navigation}, it should work because in NavButton you are calling this.props.navigator.navigate.

Share:
20,906
jackb711
Author by

jackb711

Updated on July 09, 2022

Comments

  • jackb711
    jackb711 almost 2 years

    I've been trying to get up and running with react navigation but I run into a problem when I try to move navigation items into their own components.

    HomeScreen.js

    import React, { Component } from 'react';
    
    import {
      StyleSheet,
      View,
      Text
    } from 'react-native';
    
    import NavButton from '../components/NavButton'
    
    class HomeScreen extends Component {
      render() {
        return (
          <View style={styles.container}>
            <Text>
            Hello World
            </Text>
    
            <NavButton
            navigate={this.props.navigator}
            />
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
      }
    });
    
    
    export default HomeScreen;
    

    Then in the NavButton component I try to navigate to the new screen.

     class NavButton extends Component {
      render() {
        return (
          <View>
            <Button
            title="Go to About"
            onPress={() => this.props.navigator.navigate('About')}
            />
          </View>
        );
      }
    }
    export default NavButton;
    

    But I keep getting the error "Cannot read property 'navigate' of undefined.

    Here is my Router.js file as well.

    import React from 'react';
    import {StackNavigator} from 'react-navigation';
    
    import HomeScreen from '../screens/HomeScreen'
    import AboutScreen from '../screens/AboutScreen'
    
    
    export const AppNavigator = StackNavigator({
      Home: {
        screen: HomeScreen
      },
      About: {
        screen: AboutScreen
      }
    })
    
  • jackb711
    jackb711 about 7 years
    It is still coming up with an error on the onPress function on the navButton.
  • Matt Aft
    Matt Aft about 7 years
    Oh i think its supposed to be this.props.navigation not this.props.navigator
  • jackb711
    jackb711 about 7 years
    Figured it out! The correct word to use is navigation={this.props.navigation}.
  • DMS-KH
    DMS-KH over 6 years
    How to use navigator={this.props.navigation}?