Search code examples
react-nativereact-native-navigationreact-navigation-stack

Navigation in React Native going to wrong page


I am using react-native: 0.61.4.

In app.js I have

import React from 'react';
import { View, Text } from 'react-native';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
import HomeScreen from './pages';
import ProfileScreen from './pages';

const MainNavigator = createStackNavigator({
  Home: {screen: HomeScreen},
  Profile: {screen: ProfileScreen}
});

const App = createAppContainer(MainNavigator);

export default App;

in pages.js I have

import React, { Component } from 'react';
import {  Text, View, Button } from 'react-native';

export default class HomeScreen extends React.Component {
  static navigationOptions = {
    title: 'Main Page',
  };
  render() {
    const {navigate} = this.props.navigation;
    return (
      <View style={{flex: 1}}>
        <Text>You are on the main Page</Text>
        <Button
          title="Go to Profile"
          onPress={() => navigate('Profile')}
        />
      </View>
    );
  }
}

class ProfileScreen extends React.Component {
  static navigationOptions = {
    title: 'Profile',
  };
  render() {
    return (
      <View style={{flex: 1}}>
        <Text>You are on the profile page</Text>
      </View>
    );
  }
}

On the IOS simulator, the app loads properly and shows HomeScreen. When clicking on the button though, instead of taking me to ProfileScreen like it should, it looks like it moves forward in the stack to an identical page of HomeScreen, except the page has a back button that goes back to the actual HomeScreen. Anyone know what is wrong with my navigation?


Solution

  • You are using a default export in your pages.js instead of just export HomeScreen as default switch it to:

    export { HomeScreen, ProfileScreen };
    

    So you have access to both in app.js, and import them as

    import { HomeScreen, ProfileScreen } from './pages';