Search code examples
javascriptreact-nativereact-navigationreact-component

"undefined is not an object (evaluating 'Component.router')" when running a boiler plate react-navigation app


I am new to react-native and wanted to try out react-navigation. But when I try to run a basic app it gives me 'undefined is not an object(evaluating 'Component.router)' error. Please help

here's a screenshot of the error https://i.gyazo.com/fa89defeff8bef894f509f1511f9b1ae.png

Here's the only thing I changed in the default project except for installing react-navigation and react-native-gesture-handler

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import {createAppContainer,
        createSwitchNavigator,
        createStackNavigator} from 'react-navigation';

type Props = {};
export default class App extends Component<Props> {
  render() {
    return <AppNavigator/>;
  }
}

class MainScreen extends Component{
  render(){
    return <Text>Hi</Text>
  }
}

const AppNavigator = createAppContainer(SwitchNavigator);

const SwitchNavigator = createSwitchNavigator({
  MainScreen : MainScreen,

});```



Solution

  • You have two issues in your code

    (1) You are trying to access SwitchNavigator before it's declaration. (2) You are doing MainScreen : MainScreen, which will cause an error.

    const SwitchNavigator = createSwitchNavigator({
      MainScreen,
    });
    

    or

    // optionally pass an object to your route, with screen, navigation options
    const SwitchNavigator = createSwitchNavigator({
      MainScreen: { screen: MainScreen },
    });
    
    const AppNavigator = createAppContainer(SwitchNavigator);