Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
  }
})
like image 674
jackb711 Avatar asked Sep 12 '25 07:09

jackb711


2 Answers

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.

like image 188
Matt Aft Avatar answered Sep 14 '25 22:09

Matt Aft


import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function GoToButton() {
  const navigation = useNavigation();

  return (
    <Button
      title='Screen Name'
      onPress={() => navigation.navigate(screenName)}
    />
  );
}

You can use useNavigation from @react-navigation/native with React Navigation v 5.x. More details in the documentation.

like image 37
Ujith Nimantha Avatar answered Sep 14 '25 21:09

Ujith Nimantha