Search code examples
reactjsreact-nativenavigationreact-navigation

How to navigate with react native expo?


I know it is a basic question but when I search on the web the answer is always a single file mith multiple functions link here for exemple. What I want is to use one function per file and multiple file ( I fought it would be simple like in HTML but when I look into it it seems so complicated! I only want to navigate between 2 pages!)


Solution

  • The link which you provide we only need to do the changes that we have to create new file and paste that function in new file like below

    HomeScreen.js file is looks like this

    import * as React from 'react';
    import { Button, View, Text } from 'react-native';
    Const HomeScreen = ({ navigation }) => {
      return (
          <View style={{ flex: 1, alignItems: 'center', justifyContent:   'center' }}>
           <Text>Home Screen</Text>
           <Button
            title="Go to Details"
            onPress={() => navigation.navigate('Details')}
           />
          </View>
      );
     }
     export default HomeScreen;
    

    DetailsScreen.js file is looks like this

    import * as React from 'react';
    import { Button, View, Text } from 'react-native';
    Const DetailsScreen = ({ navigation }) =>  {
    
    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
         <Text>Details Screen</Text>
         <Button
          title="Go to Details... again"
          onPress={() => navigation.push('Details')}
          />
        </View>
       );
     }
    export default DetailsScreen;
    

    And your app.js file looks like this.

    import * as React from 'react';
    import { Button, View, Text } from 'react-native';
    import { NavigationContainer } from '@react-navigation/native';
    import { createNativeStackNavigator } from '@react-navigation/native-stack';
    import HomeScreen from ‘../HomeScreen’;
    import DetailsScreen from ‘../DetailsScreen’
    const Stack = createNativeStackNavigator();
    function App() {
      return (
          <NavigationContainer>
           <Stack.Navigator initialRouteName="Home">
             <Stack.Screen name="Home" component={HomeScreen} />
             <Stack.Screen name="Details" component={DetailsScreen} />
           </Stack.Navigator>
          </NavigationContainer>
     );
    }
    
    export default App;