Create new project: expo init stacknavigation
Open project into code editor, (I’m using Visual studio code)
Install stack navigation library
npm install @react-navigation/native
npm install @react-navigation/stack
expo install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
Import stack navigation library, add these two lines
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
Create a simple page
function HomeScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
}
This is our Home Screen.
Now create an instance of stack navigator
const Stack = createStackNavigator();
Now put your Home Screen inside Navigation Container
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen}/>
</Stack.Navigator>
</NavigationContainer>
If you want to customize Header bar you can add some color into that
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} options={{
headerStyle: {
backgroundColor: '#8A2BE2',
},
headerTintColor: '#fff',
}}/>
</Stack.Navigator>
</NavigationContainer>
Now, lets navigation to another page from Home, so to do that we have to add one another UI view.
function DetailsScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
);
}
We have to make some changes into Home Screen, we have to add a navigation prop
Also we have to add Button control, when we click on button it will open detail page.
Complete Code:
import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
function 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>
);
}
function DetailsScreen() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
);
}
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} options={{
headerStyle: {
backgroundColor: '#8A2BE2',
},
headerTintColor: '#fff',
}}/>
<Stack.Screen name="Details" component={DetailsScreen} options={{
headerStyle: {
backgroundColor: '#8A2BE2',
},
headerTintColor: '#fff',
}}/>
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;