In this React Native lesson we are going to learn about React Native Navigation, we are going to use navigation 5.
Installation
First we need to install react navigation, React Navigation is made up of some core utilities and those are then used by navigators to create the navigation structure in your app.
1 |
npm install @react-navigation/native |
Now we need to install and configure some dependencies used by most navigators.
1 2 3 4 |
expo install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view |
After that we need to install navigator stack, it provides a way for our app to transition between screens where each new screen is placed on top of a stack. by default the stack navigator is configured to have the familiar iOS and Android look & feel: new screens slide in from the right on iOS, fade in from the bottom on Android. On iOS the stack navigator can also be configured to a modal style where screens slide in from the bottom.
1 |
npm install @react-navigation/stack |
First we are going to create two new simple components.
Home.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import React from 'react' import {View, Text, Button} from 'react-native'; function Home(props) { return ( <View> <Text style = {{fontSize:30, padding:50}}>Home Screen</Text> <Button title = "Profile" onPress = {() => props.navigation.navigate("Profile")}/> </View> ) } export default Home |
Profile.js
1 2 3 4 5 6 7 8 9 10 11 12 |
import React from 'react' import {View, Text} from 'react-native'; function Profile() { return ( <View> <Text style = {{fontSize:30, padding:50}}>Home Screen</Text> </View> ) } export default Profile |
This is our App.js and we have brought some changes in our this file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import { StatusBar } from 'expo-status-bar'; import React from 'react'; import {NavigationContainer} from '@react-navigation/native'; import {createStackNavigator} from '@react-navigation/stack'; import Home from './components/Home'; import Profile from './components/Profile'; const Stack = createStackNavigator() const myStyles = { title:"Home", headerTintColor:"white", headerStyle:{ backgroundColor:"green" } } function App() { return ( <Stack.Navigator> <Stack.Screen name = "Home" component = {Home} options = {myStyles} /> <Stack.Screen name = "Profile" component = {Profile}/> </Stack.Navigator> ); } export default () => { return( <NavigationContainer> <App/> </NavigationContainer> ) } |
Run your application and this is the result.