Skip to content
Advertisement

React Navigation – cannot read property ‘navigate’ of undefined

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
  }
})

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement