Hi guys, In this article, we will learn about how to navigate between screens react native. In React native we have to use the React-Navigation library to navigate between screens, you need to install this library in your project also you have to install supporting libraries which is mandatory without this libraries react-navigation will not work properly so let’s start with an example
1. Create a new project
1 |
react-native init ProjectName |
2. Install the following dependencies
1 |
npm install react-navigation |
After successful installation run the following command to install the supporting dependencies
1 |
npm install react-native-gesture-handler react-native-reanimated react-native-screens react-native-safe-area-context @react-native-community/masked-view |
finally, install the following dependency
1 |
npm install react-navigation-stack @react-native-community/masked-view react-native-safe-area-context |
3. Create CartScreen.js
I have created one screen CartScreen.js
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 |
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow strict-local */ import React from 'react'; import {SafeAreaView, View, Text} from 'react-native'; class CartScreen extends React.Component { constructor(props) { super(props); this.state = { username: 'This is cart screen', }; } static navigationOptions = ({navigation}) => { return { title: 'CartScreen', headerStyle: { backgroundColor: '#0570E9', }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold', }, }; }; render() { return ( <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}> <Text style={{fontSize: 25}}>{this.state.username}</Text> </View> ); } } export default CartScreen; |
4. App.js
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 |
import React from 'react'; import {View, Text, TouchableOpacity} from 'react-native'; import {createAppContainer} from 'react-navigation'; import {createStackNavigator} from 'react-navigation-stack'; import CartScreen from './Components/CartScreen'; <--- Import your screens class HomeScreen extends React.Component { static navigationOptions = ({navigation}) => { return { title: 'Home', headerStyle: { backgroundColor: '#0570E9', }, headerTintColor: '#fff', headerTitleStyle: { fontWeight: 'bold', }, }; }; render() { return ( <TouchableOpacity style={{flex: 1, alignItems: 'center', justifyContent: 'center'}} onPress={() => this.props.navigation.navigate('CartScreen')}> <Text style={{fontSize: 25}}>Go to Cart screen</Text> </TouchableOpacity> ); } } const AppNavigator = createStackNavigator({ Home: { screen: HomeScreen, }, CartScreen: { screen: CartScreen, }, }); export default createAppContainer(AppNavigator); |
5. Output
Thank you 🙂